syncroot

Why lock on Collection.SyncRoot instead of just lock the collection?

喜你入骨 提交于 2019-11-29 07:11:29
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

Why lock on Collection.SyncRoot instead of just lock the collection?

六月ゝ 毕业季﹏ 提交于 2019-11-28 00:48:07
问题 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 } 回答1: 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