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     }


測試結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM