根据Eric Gunnerson的说法
不
待办事项 锁定私有变量,而不是用户可以看到的东西 如果需要私钥锁定
,请使用“object key = new object()”是什么原因?
答案 0 :(得分:14)
是什么原因?
因为任何非私有的东西意味着可以从外部使用以锁定其他人或某些代码在您的控件之外导致死锁。
最佳做法是锁定私有静态变量,如下所示:
private static object _syncRoot = new object();
然后:
lock(_syncRoot)
{
...
}
私有实例变量也可能是危险的,因为类的实例不是您作为类所拥有的实现者的东西。它是拥有该实例的类的使用者。
答案 1 :(得分:2)
在发布新问题之前,您应该真正搜索旧问题。 Lock
当Darin Dimitrov说私人变量的锁定很危险时,他也错了。锁定私有变量的目的是同步类的特定实例的资源。
时会发生这种情况// A Client which listens to several servers
public class Client
{
private static object logSync = new object();
private readonly Dictionary<string, Server> servers = new Dictionary<string, Server>();// .... some code for initialization ...
// Disposing a server.
public void Dispose (string serverName)
{
// the lock needed here is on private variable. This purpose cannot be achieved with a
// lock on private static object. Well you can achieve the purpose but you will block
// all Client instances when you do so, which is pointless.
// Also notice that services is readonly, which is convenient
// because that is the object we took a lock on. The lock is on the same object always
// there is no need to unnecessarily create objects for locks.
lock(services)
{
// ... Do something cleanup here ...
Server server;
if (servers.TryGetValue(serverName, out server))
{
server.Dispose();
servers.Remove(serverName);
}
}
}
// on some message that has to be logged
public void OnMessage(string message, Server server)
{
// This makes sure that all clients log to the same sink and
// the messages are processed in the order of receipt
lock (logSync)
{
Log(evt);
}
}
}