Reputation: 8997
Let's say app startup relies on the following pattern :
public partial class App : Application
{
void App_Startup(object sender, StartupEventArgs e)
{
var config = new ConfigSettings();
var dbObjects = new DbObjects();
// many other such static classes
public class ConfigSettings
{
static ConfigSettings()
{
// long-running workload 1
// read huge xml file parse and populate cache
}
}
public class DbObjects
{
static DbObjects()
{
// long-running workload 2 :
// query db for thousands of objects populate to cache
}
}
Obviously this pattern is problematic for many reasons such as efficiency, troubleshooting, user-experience, etc.
But my question is does CLR for efficiency potentially simultaneously run code in multiple static ctors ?
Or does the CLR always guarantee that workload 1 completes before workload 2 begins, etc.
Obviously that would be guaranteed for :
public class DbObjects
{
static DbObjects()
{
var config = new ConfigSettings();
var c = new Connection(config.DbConnectionString);
// etc.
}
}
But what about cases where the ctors' code doesn't interact ?
And what about a startup code-path that kicks-off multiple long-running async processes each of which refers to one or more static classes for first time ? So it's non-deterministic the order of first reference. In this case would the CLR queue the static ctors ?
Upvotes: 3
Views: 226
Reputation: 106970
.NET will not spontaneously spawn new threads for your code. The thread that accesses the class first is the one that gets to run the static constructor at that point. If two threads access it at the same time, one will win and the other will wait until the first one is done.
Upvotes: 1