What is the best way to implement Singleton Design Pattern in C# with performance constraint?

前端 未结 2 1577
死守一世寂寞
死守一世寂寞 2020-12-06 19:17

Please let me know what the best way to implement Singleton Design Pattern in C# with performance constraint?

相关标签:
2条回答
  • 2020-12-06 19:49
    public class Singleton 
    {
        static readonly Singleton _instance = new Singleton();
    
        static Singleton() { }
    
        private Singleton() { }
    
        static public Singleton Instance
        {
            get  { return _instance; }
        }
    }
    
    0 讨论(0)
  • 2020-12-06 20:15

    Paraphrased from C# in Depth: There are various different ways of implementing the singleton pattern in C#, from Not thread-safe to a fully lazily-loaded, thread-safe, simple and highly performant version.

    Best version - using .NET 4's Lazy type:

    public sealed class Singleton
    {
      private static readonly Lazy<Singleton> lazy =
          new Lazy<Singleton>(() => new Singleton());
    
      public static Singleton Instance { get { return lazy.Value; } }
    
      private Singleton()
      {
      }
    }
    

    It's simple and performs well. It also allows you to check whether or not the instance has been created yet with the IsValueCreated property, if you need that.

    0 讨论(0)
提交回复
热议问题