14 Haz

C# Multithread Singleton Pattern Example

The singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is important when exactly one object is needed to coordinate actions across the system. Following example allows only a single thread to enter the critical area.

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

        /// 
        /// Constructor must be private.
        /// 
        private Singleton() { }

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