我知道何时在 C# 中使用 lock 块,但我不清楚的是lock variable
lock 语句的括号中。考虑以下Singleton Design Pattern
DoFactory :
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;
}
}
在上面的代码中,我不明白为什么我们不使用_instance
锁变量而不是`syncLock?