Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 462
webber Avatar asked Apr 10 '12 21:04

webber


2 Answers

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.

like image 148
Reed Copsey Avatar answered Oct 11 '22 13:10

Reed Copsey


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)

like image 31
Botz3000 Avatar answered Oct 11 '22 13:10

Botz3000