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

I have such code that runs from many threads at the same time (on common 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); } 

Dictionaries do not change throughout the life of the threads. It is safe? So far, everything is in order, but I wanted to be sure.

+4
source share
2 answers

In the dictionary, the documentation :

A dictionary can support multiple readers at once, until the collection is modified. However, enumerating through a collection is essentially not a thread safe procedure. In the rare case when an enumeration is associated with write access, the collection must be blocked during the entire enumeration. To provide access to a collection with multiple threads for reading and writing, you must implement your own synchronization.

While you never write, this should be safe.

+5
source

Only if you cannot guarantee that recordings are not performed

A dictionary (TKey, TValue) can support multiple readers at once, until the collection is changed. Even so, listing through a collection is essentially not a thread-safe procedure. In the rare case when the transfer is associated with an access record, the collection must be blocked during the entire transfer. To allow access to a collection by multiple threads for reading and writing, you must implement your own synchronization.

For an alternative that does not contain streams, see ConcurrentDictionary (Of TKey, TValue).

Shared in Visual Basic members of this type are safe threads.

Sources

+4
source

Source: https://habr.com/ru/post/1385617/


All Articles