Implementing thread safe Singleton pattern in C#

A singleton is a class which allows one instance of itself to be created and allow you to easy access to that instance. A singleton just gives you a single instance of a class. When you need a class that has only one instance. Singleton ensures you that a class has only one instance and also you have a global point to access that instance. This a simple example of singleton pattern.

 

  1.     public class ThreadSafeSingleton
  2.     {
  3.         private static volatile ThreadSafeSingleton _instance;
  4.         private static readonly object Sync= new Object();
  5.  
  6.         private ThreadSafeSingleton()
  7.         {
  8.         }
  9.  
  10.         public static ThreadSafeSingleton Instance
  11.         {
  12.             get
  13.             {
  14.                 if (_instance == null)
  15.                 {
  16.                     lock (Sync)
  17.                     {
  18.                         if (_instance == null)
  19.                         {
  20.                             _instance = new ThreadSafeSingleton();
  21.                         }
  22.                     }
  23.                 }
  24.  
  25.                 return _instance;
  26.             }
  27.         }
  28.     }

 

The benefit of implementing Singleton:

  1. Ensuring that all objects access the single instance.
  2. The class has the flexibility to change the instantiation process.
  3. By changing in one instance you can change all instances of a class.

 

 

Read these articles for complete information

  1. http://www.yoda.arachsys.com/csharp/singleton.html
  2. http://csharpindepth.com/articles/general/singleton.aspx


Tags: Design Pattern C#


comments powered by Disqus