Race condition in c# static constructor
-
30-05-2021 - |
문제
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!
해결책
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)
다른 팁
Is that even possible?
No. The CLR handles this for you, and prevents static constructors from being called more than once.
This is spelled out multiple times in the C# language specification. For example, section 3.1 states:
a static constructor for a type is run at most once per application domain.