【发布时间】:2011-02-01 03:58:01
【问题描述】:
我有一些控制器类的实例属性的代码,如下所示:
public class Controller
{
private static volatile Controller _instance;
private static object syncRoot = new Object();
private Controller() { }
public static Controller Instance
{
get
{
if (_instance == null)
{
lock (syncRoot)
{
if (_instance == null)
_instance = new Controller();
}
}
return _instance;
}
}
public void Start()
{
}
}
在阅读msdn docs on the volatile keyword 之后,我不确定第二次空检查是否是多余的,以及编写 getter 的更好方法是否是这样的:
get
{
lock (syncRoot)
{
if (_instance == null)
_instance = new Controller();
}
return _instance;
}
这两种实现中哪一种更适合多线程性能和 DRY'ness(冗余去除)?
【问题讨论】:
-
不是,锁定前要检查
标签: c#