views:

769

answers:

3

Reading msdn documentation for dictionaries it says : "Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe."

Those this mean that with a dictionary such as this :


static object syncObject = new object();
static Dictionary<string,MyObject> mydictionary= new Dictionary<string, MyObject>();

Is doing something like the code below unnecessary?


lock (syncObject)
{
   context = new TDataContext();
   mydictionary.Add("key", myObject);
}
+6  A: 

It's referring to static methods on the class itself. The statement is actually boilerplate documentation added to most classes. The Dictionary<> class doesn't actually expose any static methods.

You will have to serialize access to your dictionary class yourself using the lock keyword or perhaps even a ReaderWriterLock. Threading though is a pretty complex topic and the lock keyword isn't always appropriate. There's a great book by Joe Duffy "Concurrent Programming on Windows" that goes into great depth about protecting shared application resources.

Paul Alexander
A: 

It means that if you all the Add method (an instance method) you'd better ensure that you have exclusive access to the Dictionary by using your own locking or serialization semantics. Bad things could occur if two threads are modifying the state of your Dictionary at the same time, and it's your responsibility to ensure that this doesn't happen. There's nothing within Dictionary's Add method that will do this locking for you.

If, however, you call some static method on Dictionary (of which there aren't any useful ones) then you'd be fine without a lock.

This is the general rule for all .NET types in the BCL.

Martin Peck
+1  A: 

You are misinterpreting "public static members of this type" as "public static instances of this type".

Not Sure