Search code examples
c#race-conditionstatic-constructor

Race condition in c# static constructor


I was debating with a friend who states that the static constructor could give way to a race condition as the static constructor could be called multiple times. It seems this could only happen in high volume multi-threaded environments. Is that even possible?

I couldn't find any documentation to prove him wrong. Does anyone have any insight on this?

Thanks!


Solution

  • The static constructor is called only once per AppDomain.
    ECMA-335 states that the CLI shall guarantee that:

    "A type initializer shall be executed exactly once for any given type, unless explicitly called by user code."

    And i haven't heard of a convenient way to call type initializers in C#.

    You could only run into problems if you create circular dependencies between Type initializers.
    See here for an interesting article on that issue:
    https://msmvps.com/blogs/jon_skeet/archive/2012/04/07/type-initializer-circular-dependencies.aspx)