关于这些单例模式,我有几个问题: 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;
}
}
开锁贵吗?