Reputation: 98736
I've got code like this that's executed from many threads simultaneously (over shared a
and b
objects of type Dictionary<int, double>
):
foreach (var key in a.Keys.Union(b.Keys)) {
dist += Math.Pow(b[key] - a[key], 2);
}
The dictionaries don't change during the lifetime of the threads. Is this safe? So far, it seems OK, but I wanted to be sure.
Upvotes: 6
Views: 1368
Reputation: 5386
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.
For a thread-safe alternative, see ConcurrentDictionary(Of TKey, TValue).
Public static (Shared in Visual Basic) members of this type are thread safe.
Upvotes: 6
Reputation: 564323
From the dictionary documentation:
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.
As long as you're never writing, it should be safe.
Upvotes: 6