Search code examples
.netmultithreadingstaticinitializationstatic-initializer

Static initializers and thread synchronization (.NET)


Static initializers are supposed to be executed once before the first reference to the class. It means that every time a class is accessed, a check should be performed whether the static initializers for the class are executed.
It seems that in multithreaded environment classes with non-trivial static initializers can be a source of contention because of synchronization necessary when the class is accessed by multiple threads.
My question is what is the best way to minimize the impact of such implicit locks on the class definitions introduced by static initializers?


Solution

  • The execution of a static constructor is triggered by the first of the following events to occur within an application domain:

    • An instance of the class is created.
    • Any of the static members of the class are referenced

    It should be the responsibility of the class loader to handle concurrency issues when calling static constructors.