Why need two IF in singleton pattern in the multiple threads scenario

Refer to http://blog.163.com/xhy_cy/blog/static/1049762320112305016599/

    private readonly string connectionString;  // only can be initializable once 

    private static object syncRoot = new Object();//为了解决多线程,而添加的一个附加变量,以避免死锁



    public static SConnection Instance{

        get{

            if (instance == null){//第一个进程和第二个进程同时走到此,判断都为true
lock (syncRoot){//第一个线程锁定,在释放前不允许其他线程进入,只能等待
if (instance == null){//作用是只允许实例化一次,避免再次被实例化 instance = new SConnection(); } }
}
return instance; } }

你可能感兴趣的:(Singleton)