views:

810

answers:

2

Is simply enumerating a .NET Dictionary from multiple threads safe?

No modification of the Dictionary takes place at all.

+6  A: 

Yes, in that case enumeration is thread safe since at the beginning of a foreach loop a new instance of the enumerator is created with an implicit call to GetEnumerator.

Konrad Rudolph
Although the new enumerator(s) call back into the same underlying array. Although I dont suspect this too be a problem for reading only.
Kevin exactly. The key here is that no write access occurs at the time. As soon as you write to the hash table, all bets are off.
Konrad Rudolph
+6  A: 

Yes ... Well almost:

A Dictionary<(Of <(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.

(ref)

bruno conde