Singleton Single Instance Class in C# (Multithreaded)

Singleton Single Instance Class in C# (Multithreaded)

Added by Sixth Sense updated on Saturday, April 21, 2018

Problem:

We need a class that has only one instance, and we need to provide a global point of access to the instance. We may also want to make sure that our solution is thread safe.

using System;

public class Singleton
{
   private static Singleton _instance;

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         if (_instance == null)
         {
            _instance = new Singleton();
         }
         return _instance;
      }
   }
}			
				

The main disadvantage of this implementation, however, is that it is not safe for multithreaded environments. If separate threads of execution enter the Instance property method at the same time, more that one instance of the Singleton object may be created. Each thread could execute the following statement and decide that a new instance has to be created:

Multithreaded Singleton:

The following implementation allows only a single thread to enter the critical area, which the lock block identifies, when no instance of Singleton has yet been created:

using System;

public sealed class Singleton
{
   private static volatile Singleton _instance;
   private static object syncRoot = new Object();

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         if (_instance == null) 
         {
            lock (syncRoot) 
            {
               if (_instance == null) 
                  _instance = new Singleton();
            }
         }

         return _instance;
      }
   }
}				
				

This approach ensures that only one instance is created and only when the instance is needed. Also, the variable is declared to be volatile to ensure that assignment to the instance variable completes before the instance variable can be accessed. Lastly, this approach uses a syncRoot instance to lock on, rather than locking on the type itself, to avoid deadlocks.

Related Tags

About

29 Tutorials
25 Snippets
6 Products

More

Contact Us

Contact us

Stay Connected