Generics and collection locking
Yes, the monitor is removable over a different object in each, so the two are not functional equivalents. SyncRoot opens, so you can lock it to access a member of the collection (and the collection internally uses the same to lock). This allows the code in the collection and external code to agree on a particular lock object.
source to share
I believe there are two questions.
Same?
The answer is "it depends." It's like if SyncRoot is implemented by storing "this". IDictionary is an interface and there is no contract detailing which object should be returned for the SyncRoot property. The developer can return "this" or a completely different object (IDictionary <TKey, TValue> does this).
Is this a good idea?
Not. IDictionary developers tend to return a different object (all standard collection classes). Thus, the likelihood that you create a valid locking construct is against you.
source to share
Instead of blocking the entire dictionary, you should use the built-in version of the trusted dictionary.
http://devplanet.com/blogs/brianr/archive/2008/09/26/thread-safe-dictionary-in-net.aspx
source to share
It's very easy to see how they are not the same thing:
Monitor.Enter((IDictionary) _collection).SyncRoot));
Monitor.Exit(_collection);
This will probably throw an exception saying the object is not the same.
I would recommend using the SyncRoot object. IDictionary can simply return this
and it will actually be the same, but this is not guaranteed.
source to share