使用私有变量锁定c#

根据Eric Gunnerson的说法

  • 使用锁(这个)
  • 使用锁(typeof())

Do锁定私有变量,而不是用户可以看到的内容如果需要私钥锁定,请使用“object key = new object()”

是什么原因??

是什么原因??

因为任何非私有的东西意味着可以从外部使用来锁定其他人或某些代码,这些代码在您的控件之外导致死锁。

最好的做法是锁定私有静态变量,如下所示:

private static object _syncRoot = new object(); 

然后:

 lock(_syncRoot) { ... } 

私有实例变量也可能是危险的,因为类的实例不是您作为类所拥有的实现者的东西。 它是拥有该实例的类的使用者。

在发布新问题之前,您应该真正搜索旧问题。 锁

当Darin Dimitrov说私人变量锁是危险的时候也是错误的。 对私有变量的锁定用于同步类的特定实例的资源。 它可能发生在你有

 // A Client which listens to several servers public class Client { private static object logSync = new object(); private readonly Dictionary servers = new Dictionary();// .... 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); } } 

}