I have a class with a static constructor:
private static readonly Dictionary<string, User> UsersByName;
private static readonly Dictionary<string, User> UsersByEmail;
static MyClass() {
List<User> users = GetUsers();
UsersByName = users.ToDictionary(user => user.Name);
UsersByEmail = users.ToDictionary(user => user.Email);
}
private static List<User> GetUsers() { /* Make a WCF service call */ }
My problem was that whenever I made that WCF call, all of the worker threads in this web application died. After a lot of head scratching and binary chopping I found the root cause - it happened when we added UsersByEmail
, and moved the code into a static constructor. Changing the code to the following fixed everything.
private static readonly List<User> AllUsers = GetUsers();
private static readonly Dictionary<string, User> UsersByName = AllUsers.ToDictionary(user => user.Name);
private static readonly Dictionary<string, User> UsersByEmail = AllUsers.ToDictionary(user => user.Email);
private static List<User> GetUsers() { /* Make a WCF service call */ }
Leaving aside the bad design of calling WCF from a static constructor (which break the app until it's restarted if the service happens to be down), because that is temporary code - I'm trying to find out why the change fix this problem. I ran it in the debugger many times, with the only difference being me adding or removing an empty static constructor; the call stack is always the same meaning the web service is called at the same time, so I don't see how being called from a class without a static constructor could make any difference.