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

时间:2023-03-09 05:47:28
C# 两行代码实现 延迟加载的单例模式(线程安全)

关键代码第4,5行。

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

     public class LazySingleton
{
//Lazy singleton
private LazySingleton() { Console.WriteLine("Constructing"); }
private static readonly Lazy<LazySingleton> Linstance = new Lazy<LazySingleton>(() => { return new LazySingleton(); }); //not lazy Singleton
//public static readonly LazySingleton instance = new LazySingleton(); public String Name { get; set; }
public static LazySingleton Instance { get { return Linstance.Value; } } //For test
public static bool IsValueCreated { get { return Linstance.IsValueCreated; } }
} public class LazySingletonDemo
{
public static void Execute()
{
Task.Run(() => Foo1());
//Thread.Sleep(1000);
Task.Run(() => Foo1());
Task.Run(() => Foo1()); } public static void Foo1()
{
if (!LazySingleton.IsValueCreated)
Console.WriteLine("LazySingleton is not initialized"); LazySingleton.Instance.Name = "HK"; Console.WriteLine(LazySingleton.Instance.Name);
}
}

测试结果:

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