简体   繁体   中英

Is the SyncRoot object really thread safe?

I am new to SyncRoot concept. As far I can tell, the object used for locking should be private.

However HashTable has a public property, SyncRoot , which is just a wrapper over a private SyncRoot object. It is recommended that you lock on HashTable.SyncRoot when enumerating over the collection.

It seems like we could fail with a dead lock since it is no longer private. Is it truly thread safe?

What if I make my own private locking mechanism? private readonly object _syncObject;

Which one is better and why?

No, that isn't the real problem with the .NET 1.x approach. The property is public because it has to be publicly accessible. The trouble is with enumerating the collection. There isn't any way to implement that in a thread-safe way, there is no mechanism to automatically lock when you start enumerating and unlock when you're done. IEnumerable doesn't have a Completed method and doesn't inherit IDisposable.

So to allow code to enumerate safely, you need access to the lock object. So you can wrap the foreach statement with a lock on that object. Thus the public SyncRoot property.

The biggest bear trap that many programmers fell into however was assuming that wasn't necessary. Buying into the notion that the Synchronized property returns a thread-safe wrapper for the collection that's thread-safe in all circumstances. It isn't.

ICollection.SyncRoot is only on the pre-generic collections. It's basically been obsoleted.

This was removed in the generic collections for exactly the reasons you mention - you should use your own locking mechanism for controlling access to collections that has the properties you need (keeping the locking private, avoiding deadlocks...), rather than using the SyncRoot object and then assuming your code is magically thread-safe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM