Thread-Safe Singleton Design Pattern in C#

 

In my previous article we discuss about Lazy-instantiation and Eager-instantiation singleton design pattern. Lazy-instantiation design pattern is the multi-threaded design pattern, we don’t have thread safe. Eager-instantiation is the Singleton-thread safe pattern. In this article we discuss about one more way for thread-safe singleton design pattern. 

Basically C# is the multi-threaded language, means at once multiple threads will execute. We can avoid multiple threads by using lock keyword as shown below. 

namespace CSharpSingletonDesignPattern 

{ 

    ///<summary> 

    /// class declare with public and sealed keywords 

    /// sealed: to avoid inheritance from other class 

    /// public: for global access 

    ///</summary> 

    public sealed class CEO 

    { 

        #region Thread-Safe Singleton         

        private static CEO singleton = null; 

        private static readonly object singletonLock = new object();

 

        static CEO() 

        { 

        }

 

        private CEO() { }

 

        public static CEO GetInstance() 

        { 

            lock (singletonLock) 

            { 

                if (singleton == null) 

                { 

                    singleton = new CEO(); 

                } 

                return singleton; 

            } 

        } 

        #endregion 

    } 

}

 

As shown above we have the singletonLock object. We lock the singletonLock object in GetInstance() method before creating the object. At a time only one thread will execute, if second thread is trying to execute it has to wait until first thread release that object. 

                                                                                                            CSharpThreadSafeSingleton.zip (43.01 kb)