问题描述
我想了解的ICollection SyncRoot上的点。为什么不直接锁定集合?
锁(myCollection)将
{
//做的东西到MyCollection中
}
VS
锁(myCollection.SyncRoot)
{
//做的东西到MyCollection中
}
通常情况下,如果线程安全是一个严重的问题,我会避免这些选项之一。
有一个更好的选择通常是保持你的自己的私有变量的,并且它在它所需的所有锁的方法 - 包括访问集合整个公共API
真正的危险在于,通过锁定上的裸或可能暴露给外界一个类型,你可能开拓能力的外面的世界来惹你同步。如果使用一个以上的锁,这可能会导致死锁(如果你不期待的东西外面的锁)。
通过创建一个私有变量,并对其独占锁,你是控制的局面。这使得它更清楚发生了什么问题。此外,它简化了同步多个对象之间,尤其是以后你保持在code,因为锁是很清楚的。
I'm trying to understand the point of the syncroot in ICollection. Why not just lock the collection?
lock(myCollection)
{
//do stuff to myCollection
}
vs
lock(myCollection.SyncRoot)
{
//do stuff to myCollection
}
Typically, if thread safety is a serious concern, I would avoid either of these options.
A far better option is typically to maintain your own private variable, and lock on it in all methods where it's required - including the entire public API that accesses the collection.
The real danger is that, by locking on a type that's exposed or could be exposed to the outside world, you potentially open up the ability for the "outside world" to mess with your synchronization. If more than one lock is being used, this can lead to dead locks (if the outside locks on something you aren't expecting).
By creating a private variable, and locking exclusively on it, you're "taking control" of the situation. This makes it much more clear what is occurring. In addition, it eases synchronization between multiple objects, especially later as you maintain the code, since the lock is very clear.
这篇关于为什么锁Collection.SyncRoot而不是只锁定集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!