tags:

views:

253

answers:

5

is there any difference between:

lock((IDictionary) _collection).SyncRoot)

or

lock(_collection)
+4  A: 

Yes, the Monitor is take out on a different object in each, so the two are not functional equivalents. The SyncRoot is exposed so you can lock on it for collection member access (and the collection internally uses the same for locking). This allows code in the collection and code external to it to agree upon a specific lock object.

ctacke
A: 

That depends on the implementation of the IDictionary. If the dictionary returns "this" as the SyncRoot, the statements are equivalent.

Rauhotz
A: 

It's really easy to see how it is not the same:

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. The IDictionary may simply return this and it will effectively be the same, but that's not guaranteed.

Martinho Fernandes
what do you mean "may" be the same. If the implementation is Dictionary<string, string>
ooo
I said that in my answer. "The IDictionary may simply return this and it will effectively be the same, but that's not guaranteed."
Martinho Fernandes
+4  A: 

I believe there are two questions.

Is it the same?

The answer to this is "it depends." It is only the same if SyncRoot is implemented by returing "this". IDictionary is an interface and there is no contract detailing what object should be returned for the SyncRoot property. The implementor is free to return "this" or a completely different object (IDictionary<TKey,TValue> does this).

Is it a good idea?

No. IDictionary implementors tend to return a different object (all of the standard collection clasess do). So the odds are against you in creating a valid locking construct.

JaredPar
+1  A: 

You should use a native Thread Safe Dictionary implementation instead of locking the entire Dictionary.

http://devplanet.com/blogs/brianr/archive/2008/09/26/thread-safe-dictionary-in-net.aspx

Yoann. B