leora
leora

Reputation: 196751

Generics and locking on collections

is there any difference between:

lock((IDictionary) _collection).SyncRoot)

or

lock(_collection)

Upvotes: 0

Views: 516

Answers (5)

Yoann. B
Yoann. B

Reputation: 11143

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

Upvotes: 1

JaredPar
JaredPar

Reputation: 755269

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.

Upvotes: 4

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234654

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.

Upvotes: 0

Rauhotz
Rauhotz

Reputation: 8150

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

Upvotes: 0

ctacke
ctacke

Reputation: 67188

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.

Upvotes: 4

Related Questions