Exemplo n.º 1
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public static LazySingleton GetInstance()
        {
            if (Instance == null)
            {
                Instance = new LazySingleton();
            }

            return(Instance);
        }
Exemplo n.º 2
0
        public static void Main(string[] args)
        {
            EagerSingleton eagerSingleton = EagerSingleton.GetInstance();

            Console.WriteLine(eagerSingleton.ToString());

            LazySingleton lazySingleton = LazySingleton.GetInstance();

            Console.WriteLine(lazySingleton.ToString());
        }
Exemplo n.º 3
0
 public static LazySingleton GetInstance()
 {
     if (_instance == null) //第一重判断,先判断实例是否存在,不存在再加锁处理
     {
         lock (_lock)       //加锁的程序在某一时刻只允许一个线程访问
         {
             //第二重判断
             if (_instance == null)
             {
                 _instance = new LazySingleton();
             }
         }
     }
     return(_instance);
 }
Exemplo n.º 4
0
        readonly static Object obj = new object();//限制只在静态初始化时 obj有实例

        public LazySingleton GetLazySingleton()
        {
            if (lazySingleton == null) //这里线程不安全
            {
                lock (obj)             //当两者同时到此,但是都没有初始化,且是排队的,但这时会有一个进去初始化成功,但是下一个也会进去,因此还需要一层判断,即前者是否初始化成功了
                {
                    if (lazySingleton != null)
                    {
                        return(lazySingleton);
                    }
                    lazySingleton = new LazySingleton();
                    return(lazySingleton);
                }
            }
            return(lazySingleton);
        }
Exemplo n.º 5
0
        public static LazySingleton GetInstance(string value)
        {
            if (_instance == null)
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        _instance       = new LazySingleton();
                        _instance.Value = value;
                    }
                }
            }

            return(_instance);
        }
Exemplo n.º 6
0
 /// <summary>
 /// 双重检查 解决多线程问题
 /// </summary>
 /// <returns></returns>
 public static LazySingleton GetInstance()
 {
     // 第一重判读,实例是否存在,不存在加锁处理
     if (instance == null)
     {
         // 加锁的程序在某一刻只允许一个线程访问
         lock (obj)
         {
             //第二重判断
             if (instance == null)
             {
                 //创建单例实例
                 instance = new LazySingleton();
             }
         }
     }
     return(instance);
 }
Exemplo n.º 7
0
        private static void TestSingleton(string value)
        {
            var singleton = LazySingleton.GetInstance(value);

            Console.WriteLine(singleton.Value);
        }