我正在创建一个像这样的对象:
if (_cleaner == null)
{
_creation.WaitOne();
try
{
if (_cleaner == null)
{
//create object
}
}
finally
{
_creation.ReleaseMutex();
}
}
我进行双重检查的原因是因为两个线程可以同时进行对象创建,然后我显然只需要一个线程即可创建对象。有更好的方法吗?
所以我不必两次检查对象是否存在?
最佳答案
您可能要使用Lazy<T>
,它的语法更简洁,而error-prone than double check locking更少。
它可以帮助您创建一个仅在首次访问时初始化一次的对象(lazy initialization),我认为语法是不言自明的,一些用法示例在this MSDN article中,我将举一个例子:
class Customer
{
private Lazy<Orders> _orders;
public string CustomerID {get; private set;}
public Customer(string id)
{
CustomerID = id;
_orders = new Lazy<Orders>(() =>
{
// You can specify any additonal
// initialization steps here.
return new Orders(this.CustomerID);
});
}
public Orders MyOrders
{
get
{
// Orders is created on first access here.
return _orders.Value;
}
}
}
关于c# - 互斥对象创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23171606/