Exemple #1
0
        //public static DaoSingleton Instance
        //{
        //    get
        //    {
        //        if (_instance == null)
        //        {
        //            lock (key)
        //            {
        //                if (_instance == null)
        //                {
        //                    _instance = new DaoSingleton();
        //                }
        //            }
        //        }
        //        return _instance;
        //    }
        //}

        public static DaoSingleton GetInstance()
        {
            if (_instance == null)
            {
                System.Console.WriteLine($"In if(). before lock(). Thread: {Thread.CurrentThread.Name}");
                lock (key)
                {
                    System.Console.WriteLine($"In lock(). Before if(). Thread: {Thread.CurrentThread.Name}");
                    if (_instance == null)
                    {
                        System.Console.WriteLine($"In lock() and inside the last if(). Thread: {Thread.CurrentThread.Name}");
                        _instance = new DaoSingleton();
                    }
                }
            }
            return(_instance);
        }
Exemple #2
0
        static void GetThreadsafeSingleton()
        {
            var singleton = DaoSingleton.GetInstance();

            Console.WriteLine($"Thread: {Thread.CurrentThread.Name}\tSingleton: {singleton.GetHashCode()}");
        }