Cameron
Cameron

Reputation: 98736

Is it safe to iterate over an unchanging dictionary from multiple threads?

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

Answers (2)

Will Bickford
Will Bickford

Reputation: 5386

Only if You Guarantee No Writes Occur

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.

Sources

Upvotes: 6

Reed Copsey
Reed Copsey

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

Related Questions