Design thread safe Singleton Class in C# Considering Performance

(Last Updated On: February 26, 2019)

In, C# programming, Singleton in multi-threaded environment can produce more than one objects of singleton class if not designed properly. Where singleton class is expected to return only one of its instance. In this section, we will design the thread safe singleton class which was not designed in the answer of C# technical interview question i.e. explain C# singleton class example which is recommended to read before continuing to thread safe singleton class design.

 

In multi-threaded environment, multiple threads can enter into GetInstance() method’s if condition when object is getting created first time. So, there is chance for more than one object creation. But, singleton class target is to create only one object.

So, we have to put lock in this block so only one thread can enter and create object.

 

 

Let’s put the lock to avoid multiple object creation. Below function design ensures for a single object creation.

 

 

But, there is a performance issue now. Let’s say GetInstance() method is getting called again and again during program execution then every time it will check the lock making application slow.

To avoid performance issue, better solution is to put one more if condition to avoid calling locks.

Below piece of code will avoid lock performance issue with singleton thread safe double check concept.

 

 

Thread Safe Singleton class example design – Complete C# Program Example :