关键代码第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 LazyLinstance = new Lazy (() => { 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 test14 public static bool IsValueCreated { get { return Linstance.IsValueCreated; } }15 }16 17 public class LazySingletonDemo18 {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 }