Search code examples
c#constructorstatic-constructor

Is there any chance a instance of a class (regular ctor) will be created before the static ctor completes it's run (in a multi-threaded environment)?


I have a static ctor that fetches a configuration from my configuration server and sets a static variable.

I have a regular ctor that instantiates some properties based on that configuration.

Here's an example of my class:

public class MyClass
{
   private static MyConfig _config;
   private UnitOfWork _uow;

   static MyClass(){
        // This takes some time since it's a web service call!!!
        _config = ConfigService.GetConfig(); 
   }

   public MyClass(){
        _uow = CreateUow(_config.UOWConnectionString);
   }

   public Response DoSomething(){
       // logic with _uow
   }
}

Assuming I have a WCF service that receives multiple requests, each request instantiates MyClass and runs the DoSomething method.

The static ctor performs a web service call that takes some time until it gets the result.

Can I be sure that the static ctor will finish running before any request will receive an instance of MyClass?

I know that static ctors are thread safe.

Is there any lock on creating new instances until the static ctor completes to run?


Solution

  • Static constructors are guaranteed to be run before any instance is created. From MSDN.

    A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.