24

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)?

Francois Nel
  • 1,662
  • 2
  • 19
  • 29
  • You'll have only one instance, but it won't be thread-safe. You must implement your access control to it (`Mutex` or whatever). – Andre Calil Aug 28 '12 at 12:55
  • 4
    I know the instance members of the class still need to be thread-safe, my question is is the initialisation of the readonly static fields thread-safe (i.e. will the static constructor only ever be called by one thread?) – Francois Nel Aug 28 '12 at 13:00
  • 1
    It will be called just once by the runtime. It's like you had a *singleton* to the whole application. – Andre Calil Aug 28 '12 at 13:01
  • 3
    There will be an instance of `MyClass` per `AppDomain`. – João Angelo Aug 28 '12 at 13:18

2 Answers2

30

.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.

Kash
  • 8,799
  • 4
  • 29
  • 48
  • *".NET CLR ensures that static initialisation is always thread-safe."* this is true **unless** someone is trying to do **really weird** things. Like this code will result in deadlock: `using System.Threading; class Foo { static void Main() { } static Foo() { Thread thread = new Thread(arg => { }); thread.Start(); thread.Join(); } }` – oleksii Aug 28 '12 at 19:06
  • Another exception would be marking a static member as ThreadStatic. – Tarec Aug 17 '13 at 00:31
10

The class initialization is guaranteed by the specification of the C# language to be thread safe, so only one instance of MyClass will be created. You would have to ensure thread safety from that point onwards yourself. Here's an MSDN reference:

http://msdn.microsoft.com/en-us/library/aa645612.aspx

David M
  • 71,481
  • 13
  • 158
  • 186