Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
650 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...