Dictionaries and Threads

    Back on March 27th, I posted the entry "Thread synchronization with Collections".  That information came from a .Net Threading class I had taken that was taught by a very prominent .Net teacher (who’s initials are JR).   The topic came up in class about how to safely assign to a dictionary entry.  Somehow I had come away with the notion that mydictionary["mykey"] = value was thread safe.  Apparently that was something that was brought up in class and was just never refuted.  When I asked the instructor about it, he simply responded with "Dictionary is NOT thread-safe for any operation." (no comment was made about the fact that it was brought up in class).
   Therefore, I have removed that posting.  According to the MSDN:
Thread Safety

Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

A Dictionary can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with write accesses, the collection must be locked during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

This just goes to show you that you should always test the information you come across to validate it.  Especially when (1) you have some doubts about it and (2) it’s too good to be true.




About JohnHowell

I am a professional software developer with over 20 years of experience. I currently specialize in Microsoft technologies such as VS, TFS, C#, VB.Net, WCF, WPF, WW, etc.
This entry was posted in Performance. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s