我对此处记录的单例模式有一些疑问: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;
}
}
}
具体来说,在上面的示例中,是否需要在锁之前和之后两次将实例比较为null?这有必要吗?为什么不先执行锁定并进行比较?
简化为以下内容是否有问题?
public static Singleton Instance
{
get
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
return instance;
}
}
执锁昂贵吗?