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.
Asked
Active
Viewed 1,655 times
1
-
1[Dictionary
- Thread Safety](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=net-6.0#thread-safety) – Fildor Dec 14 '21 at 08:37 -
1No, it's not thread safe for write and remove operation(s). You should use a ConcurrentDictionary – Rasmus Søborg Dec 14 '21 at 08:39
-
6As a general rule, check the documentation and unless it explicitly states that it **is** thread-safe, then the rule is that it **isn't**. – Lasse V. Karlsen Dec 14 '21 at 08:48
-
1@RasmusSøborg How do you know, OP should use a ConcurrentDictionary? Dpending on what he is actually doing, this _could_ be really bad advice. – Fildor Dec 14 '21 at 08:55
1 Answers
9
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.

Zohar Peled
- 79,642
- 10
- 69
- 121