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     }


    测试结果:

  • 相关阅读:
    题目1449:确定比赛名次
    题目1005:Graduate Admission
    HDU 4786 Fibonacci Tree
    FZU Problem 2136 取糖果
    iOS 递归锁
    iOS xcode问题集结
    iOS 芝麻认证开发(跳转本地的支付宝进行认证开发)
    iOS导出ipa包时四个选项的意义
    两排按钮循环
    Masony 常用方法
  • 原文地址:https://www.cnblogs.com/1zhk/p/5257340.html
Copyright © 2011-2022 走看看