views:

48

answers:

2

In C#, can multiple threads read and write to a Dictionary provided each thread only accesses one element in the dictionary and never accesses another?

+3  A: 

No, they can't. A dictionary is not thread safe:

A Dictionary(TKey, TValue) 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.

Darin Dimitrov
Is there an alternative?
Sir Psycho
Yes, in C# 4.0 there's the `ConcurrentDictionary` class (http://msdn.microsoft.com/en-us/library/dd287191(VS.100).aspx) and in C# 3 you will have to implement a synchronization mechanism (`lock`, `ReaderWriterLockSlim`, ...)
Darin Dimitrov
+4  A: 

No, a Dictionary is not Thread-safe.

With the exception of modifying the contents of a reference type (object) that is stored as the Value in a dictionary.

In .NET 4 we will have System.Collections.Concurrent.ConcurrentDictionary.

Henk Holterman