我对这里记录的单例模式有一些疑问:http: //msdn.microsoft.com/en-us/library/ff650316.aspx
以下代码摘自文章:
using System;
public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new object();
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
具体来说,在上面的例子中,是否需要在锁之前和之后将 instance 与 null 进行两次比较?这是必要的吗?为什么不先执行锁定并进行比较?
简化为以下是否有问题?
public static Singleton Instance
{
get
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
return instance;
}
}
执行锁是否昂贵?