Three ways to write the singleton pattern c#

// The first one is the simplest, but it does not consider thread safety, it may cause problems in multi-threading, but I have never seen the phenomenon of errors 
public  class Singleton
{
    private static Singleton _instance = null;
    private Singleton(){}
    public static Singleton CreateInstance()
    {
        if(_instance == null)

        {
            _instance = new Singleton();
        }
        return _instance;
    }
}

// The second one considers thread safety, but it's a bit annoying, but it's definitely a regular way of writing, a classic fork

public class Singleton
{
    private volatile static Singleton _instance = null;
    private static readonly object lockHelper = new object();
    private Singleton(){}
    public static Singleton CreateInstance()
    {
        if(_instance == null)
        {
            lock(lockHelper)
            {
                if(_instance == null)
                     _instance = new Singleton();
            }
        }
        return _instance;
    }
}

// The third may be unique to high-level languages ​​such as C#, which is really lazy

public class Singleton
{

    private Singleton(){}
    public static readonly Singleton instance = new Singleton();
}  

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324660902&siteId=291194637