Ehsan Ghanbari

Experience, DotNet, Solutions

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

About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns. I spend a lot of time on software architecture. Since 2008, I've been as a developer for different companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the past years, Read More

Post Tags
Pending Blog Posts
using Elmah in asp.net MVC4
Using FluentSecurity in MVC
Strategic design
Factory Pattern
time out pattern in ajax
Redis as a cache server
How to use PagedList In asp.net MVC
Multiple submit buttons in asp.net MVC
Domain driven design VS model driven architecture
What's the DDD-lite?
comments powered by Disqus