【发布时间】:2011-10-30 21:34:09
【问题描述】:
根据埃里克·冈纳森的说法
不要
- 使用锁(这个)
- 使用锁(typeof())
做 锁定私有变量,而不是用户可以看到的东西 如果您需要私钥来锁定,请使用“object key = new object()”
是什么原因??
【问题讨论】:
标签: c# synchronization
根据埃里克·冈纳森的说法
不要
做 锁定私有变量,而不是用户可以看到的东西 如果您需要私钥来锁定,请使用“object key = new object()”
是什么原因??
【问题讨论】:
标签: c# synchronization
是什么原因??
因为任何不是私有的东西都意味着可以从外部被其他人使用来锁定,或者某些不受您控制的代码会导致死锁。
最佳做法是锁定私有静态变量,如下所示:
private static object _syncRoot = new object();
然后:
lock(_syncRoot)
{
...
}
私有实例变量也可能是危险的,因为你的类的实例不是你作为类的实现者拥有的东西。它是拥有该实例的类的消费者。
【讨论】:
this,你的代码的消费者,因为它拥有你的类的一个实例,也可以尝试锁定这个实例,而不知道你在内部也在尝试锁定同一件事。以下是一些示例:stackoverflow.com/questions/894037/…
在发布新问题之前,您应该真正搜索旧问题。 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);
}
}
}
【讨论】: