Generics and collection locking

is there any difference between:

lock((IDictionary) _collection).SyncRoot)

      

or

lock(_collection)

      

0


source to share


5 answers


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.



+4


source


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.

+4


source


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

+1


source


It depends on the implementation of IDictionary. If the dictionary returns " this

" like SyncRoot

, the statements are equivalent.

0


source


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.

0


source







All Articles