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