Home > database >  Is Dictionary<Key, value> is thread safe for read, write and remove operation
Is Dictionary<Key, value> is thread safe for read, write and remove operation

Time:12-15

We are using dictionary in our application to maintain data process using thread. In this application some thread performing read, write and delete operation. Is Dictionary<Key, value> is thread safe for read, write and remove operation.

CodePudding user response:

No. A dictionary is not thread safe.
In fact, it's documentation specifically states that -

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.

For thread-safe alternatives, see the ConcurrentDictionary<TKey,TValue> class or ImmutableDictionary<TKey,TValue> class.

  • Related