C# 两行代码实现 延迟加载的单例模式(线程安全)

关键代码第4,5行。

很简单的原理不解释:readonly + Lazy(.Net 4.0 + 的新特性)

 1     public class LazySingleton
 2     {
 3         //Lazy singleton
 4         private LazySingleton() { Console.WriteLine("Constructing"); }
 5         private static readonly Lazy<LazySingleton> Linstance = new Lazy<LazySingleton>(() => { return new LazySingleton(); });
 6 
 7         //not lazy Singleton
 8         //public static readonly LazySingleton instance = new LazySingleton();
 9 
10         public String Name { get; set; }
11         public static LazySingleton Instance { get { return Linstance.Value; } }
12 
13         //For test
14         public static bool IsValueCreated { get { return Linstance.IsValueCreated; } }
15     }
16 
17     public class LazySingletonDemo
18     {
19         public static void Execute()
20         {
21             Task.Run(() => Foo1());
22             //Thread.Sleep(1000);
23             Task.Run(() => Foo1());
24             Task.Run(() => Foo1());
25           
26         }
27 
28         public static void Foo1()
29         {
30             if (!LazySingleton.IsValueCreated)
31                 Console.WriteLine("LazySingleton is not initialized");
32 
33             LazySingleton.Instance.Name = "HK";
34 
35             Console.WriteLine(LazySingleton.Instance.Name);
36         }
37     }


测试结果:

原文地址:https://www.cnblogs.com/1zhk/p/5257340.html