Thread safety on readonly static field initialisation

c#, multithreading, thread-safety

Solution

.NET CLR ensures that static initialization is always thread-safe. No matter how many threads are accessing it and what order, it will always be initialized once.

Your code seems to show signs of the beginnings of a Singleton pattern. Basically if you want to run custom code before you initialize the class, then you need to ensure thread-safety on your own. This is an example where you would need to make your custom code thread safe. But the static initialization part is always thread safe.

Problem

If one creates a readonly static member like this: ``` public sealed class MyClass { public readonly static MyClass Instance = new MyClass(); } ``` We know that the static constructor will initialise the MyClass.Instance field if some thread accesses MyClass the fist time. But, will a single instance (in this case MyClass) be created if multiple threads all accesses MyClass at the same time (i.e. is the initialisation of the static field thread-safe)?

Original source