是否有任何理由而除新对象以外的其他锁定()? [英] Is there any reason to lock on something other than new object()?
问题描述
object theLock = new object();
...
lock (theLock)
{
...
}
我总是使用新的对象()
这一点,但我想知道:是否有任何情况下,您会在一个更具体的类型锁定
I always use a new object()
for this, but I'm wondering: are there any circumstances in which you would lock on a more specific type?
推荐答案
在情况下,新
的键入
没关系,实例做。在这种情况下,你是在谈论一个的SyncLock 的对象:一个对象,它是用来锁定code(S)部分(S)以prevent并发访问
In case of a new
, the Type
doesn't matter, the instance do. In this case you're talking about a synclock object : an object which is used to lock code(s) section(s) to prevent concurrent access.
使用另一个键入
比对象
的的SyncLock是浪费内存,因为你不使用该实例为别的。
Using another Type
than object
for a synclock is a waste of memory because you don't use this instance for anything else.
目前是在何种情况下可以锁定另一种类型:当你需要锁定一个具体的实例。 主要的问题是:该实例必须初始化其锁定。在大多数情况下,要SYNCLOCK实例的动初始化:)
There're circumstances in which you can lock another type : when you need to lock a specific instance. The main problem is : the instance must be initialized to lock it. And in most cases, you want to synclock the initilization of the instance :)
但在某些情况下,可以直接锁定实例;例如像(在此情况下也几乎直接)字典)
But in some case, you can lock the instance directly ; like a dictionary for example (well almost directly in this case ;)).
private Dictionary<string,string> _dictionary = new Dictionary<string,string>();
public void AddValue(string key, string value)
{
lock (((IDictionary)_dictionary).SyncRoot) // SyncRoot recommended
{
if (!_dictionary.ContainsValue(value))
_dictionary.Add(key, value);
}
}
但问题是:即使这会的工作,总是问自己:这不是一个好主意,以创建一个特定的锁定对象,而不是
But the point is : even if this will work, always ask yourself : "Is it not a better idea to create a specific locking object instead" ?
这篇关于是否有任何理由而除新对象以外的其他锁定()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!