IVth way of implementing Singleton Pattern in C#: Multithreaded Singleton Pattern
When there is need for multithreaded environment or the ability to use a non default constructor or ability to perform some tasks before the instantiation is done the earlier approach will fail and we need to go for different approach. There might be situation when we cannot rely relying on the CLR to take care of thread safety. In such a situation the language advantage can be taken to ensure single instance of object is created among many threads. The solution for this is to use the Double-Check Locking to keep separate threads from creating new instances of the singleton class at the same time.
The following implementation allows only a single thread to lock as against the above mentioned flaw, when no instance of Singleton has yet been created:
using System;
public sealed class SingletonExample
{
private static volatile SingletonExample instance;
private static object objectlockCheck = new Object();
private SingletonExample () {}
public static SingletonExample Instance
{
get
{
if (instance == null)
{
lock (objectlockCheck)
{
if (instance == null)
instance = new SingletonExample ();
}
}
return instance;
}
}
}
In this way only one instance can is created and that to when there is a need for class instance. Also, the variable is declared as volatile which ensures that assignment to the instance variable is completed before the instance variable can be accessed. Finally, this approach uses an object of type objectlockCheck instance to lock on, rather than locking on itself, to avoid deadlocks. This double-check locking approach solves the thread concurrency problems this also avoids an exclusive locking with every call to the Instance property method.
Conclusion
You can see that the last implementation provides best performance, thread safety, and robustness, however there is complicated code involved with it. Similarly there can be tradeoffs between various important aspects before choosing a pattern.