Reputation: 17498
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?
Upvotes: 3
Views: 837
Reputation: 273244
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
.
Upvotes: 4
Reputation: 1038800
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.
Upvotes: 3