Is this Singleton implementation correct and thread-safe?

后端 未结 4 2136
北荒
北荒 2020-12-15 12:14

Is this singleton implementation correct and thread-safe?

class Class
{
    public static readonly Class Instance;

    static Class()
    {
        Instance         


        
相关标签:
4条回答
  • 2020-12-15 12:53

    Technically, your version should work. However, I would not recommend exposing a public field within your Singleton class, and prefer using a Property (with a getter only). This will help future-proof your API if you need to make changes later. I also recommend sealing any singleton implementation, as subclassing a singleton class is almost always a bad idea and problematic.

    I would, personally, use the following in C#, if you're targetting .NET 3.5 or earlier:

    public sealed class Singleton
    {
        static readonly Singleton instance = new Singleton();
    
        public static Singleton Instance
        {
            get
            {
                return instance;
            }
        }
    
        static Singleton() { }
        private Singleton() { }
    }
    

    If you're using .NET 4, you can make this even easier for yourself via Lazy<T>:

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

    The .NET 4 version also has the advantage of being fully lazy - even if your Singleton class has other static methods which are used prior to the access of the "Instance" property. You can do a fully-lazy .NET 3.5- version, as well, by using a private, nested class. Jon Skeet demonstrated this on his blog.

    0 讨论(0)
  • 2020-12-15 12:59

    Good discussion of how to do that is here:

    http://www.yoda.arachsys.com/csharp/singleton.html

    0 讨论(0)
  • 2020-12-15 13:06

    You should do the initialization in the variable declaration:

    public static readonly Class Instance = new Class();
    
    0 讨论(0)
  • 2020-12-15 13:10

    Yes. I would also make the class 'sealed' to avoid any future confusion.

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