I was under the impression that static initialization is thread safe by default. Is that correct? Also consider the below example of singleton pattern.
public sealed class SingletonDemo
{
private static readonly SingletonDemo instance = new SingletonDemo();
private SingletonDemo()
{}
public static SingletonDemo Instance
{
get
{
return instance;
}
}
}
Is above example thread safe? If yes why? If No why?
I was under the impression that static initialization is thread safe by default. Is that correct?
Yes, in terms of initialization - unless you use reflection to call the type initializer again, etc. Of course, there can then be multiple threads accessing the singleton at a time, so you need to make sure that instance members are thread-safe.
Note that with C# 6, the code can be simplified to:
public sealed class SingletonDemo
{
public static SingletonDemo Instance { get; } = new SingletonDemo();
private SingletonDemo() {}
}
The type initialization rules of the CLR ensure that:
With the code as it is, laziness is not guaranteed - in other words, SingletonDemo
may be initialized even if it's never actually used (e.g. because a method is called which conditionally uses it, but the condition isn't hit). To make it fully lazy, you could either use Lazy<T>
or a static initializer:
public sealed class SingletonDemo
{
public static SingletonDemo Instance { get; } = new SingletonDemo();
private SingletonDemo() {}
private static SingletonDemo() {}
}
See more on this question at Stackoverflow