Blog

Filter posts by Category Or Tag of the Blog section!

Implementing thread safe Singleton pattern in C#

Tuesday, 15 October 2013

A singleton is a class which allows one instance of itself to be created and allow you to easily 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 a singleton pattern.

 

    public class ThreadSafeSingleton
    {
        private static volatile ThreadSafeSingleton _instance;
        private static readonly object Sync= new Object();

        private ThreadSafeSingleton()
        {
        }

        public static ThreadSafeSingleton Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (Sync)
                    {
                        if (_instance == null)
                        {
                            _instance = new ThreadSafeSingleton();
                        }
                    }
                }

                return _instance;
            }
        }
    }

 

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

Category: Software

Tags: C#

comments powered by Disqus