No, Dictionary<TKey, TValue>
class is not thread-safe for modification, as can be seen in the documentation:
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.
In your case, if some threads will finish the LongTaskToGenerateString
almost simultaneously their dictionary updates will interference.
You might either use the SyncRoot
property to synchronize the access manually, or just take the ConcurrentDictionary<TKey, TValue>
class, as suggested by asawyer in the comments.
This implementation suggests that if you're only updating the values for existing keys, it should be OK (looking also at this) - the inelegant effect could be inaccurate value of the version
property. It is used to guard against modifying the collection while it's being enumerated, so it doesn't really matter at which value it will end up. Don't know about any guarantees about this though.