我知道何时在C#中使用锁定块,但是我不清楚的是锁定语句括号中的lock variable
。考虑以下Singleton Design Pattern
从DoFactory:在上面的代码C#中的锁定变量#
class LoadBalancer
{
private static LoadBalancer _instance;
private List<string> _servers = new List<string>();
private static object syncLock = new object();
public static LoadBalancer GetLoadBalancer()
{
// Support multithreaded applications through
// 'Double checked locking' pattern which (once
// the instance exists) avoids locking each
// time the method is invoked
if (_instance == null)
{
lock (syncLock)
{
if (_instance == null)
{
_instance = new LoadBalancer();
}
}
}
return _instance;
}
}
,我不明白为什么我们不锁变量,而不是`SYNCLOCK使用_instance
?
为什么编译器使用syncLock?这个变量有什么好处? –
@SeyedMortezaMousavi:你是什么意思“为什么编译器使用syncLock?”它不是编译器,它是开发人员......关键是确保只有一个线程输入创建LoadBalancer实例的代码。 –
你需要锁定一个对象。这就是它的全部。 –