zoukankan      html  css  js  c++  java
  • 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     }


    测试结果:

  • 相关阅读:
    第八周作业
    第七周上机作业2
    神经网络基础
    [网鼎杯 2020 青龙组]AreUSerialz
    BJDCTF 2nd old-hack
    php反序列化漏洞学习
    CTFHUB-HTTP协议
    ctfhub-密码口令
    CTFHUB-信息泄漏
    buuctf-[BJDCTF 2nd]elementmaster
  • 原文地址:https://www.cnblogs.com/1zhk/p/5257340.html
Copyright © 2011-2022 走看看