Search code examples
c#multithreadingconcurrent-collections

Concurrent collections is it safe to modify from different threads


Let say I have:

MyCollection = new ConcurrentDictionary<string, int>();

I now it is safe to add and remove items from MyCollection . But What about modifying items. For example is it safe to do:

MyCollection["key"] = 1;   // thread 1

and

MyCollection["key"] = 2;   // thread 2

Example 2:

MyCollection2 = new ConcurrentDictionary<string, List<int>>();

Is it safe to do?

MyCollection2["key"].Add(1);  // Thread1

and

MyCollection2["key"].Add(2);  // Thread2

where Thread1 and Thread2 are executing at the same time. Do I have to create a lock when modifying items?


Solution

  • Whether or not it is safe to modify the item is entirely independent on whether or not it is in a ConcurrentDictionary. That's no different than just having a list that you mutate from two different threads. In the case of List, it's not safe; if you use a type that is designed to be mutated from multiple different threads, such as a ConcurrentDictionary<string, ConcurrentQueue<int>> then that would be fine.

    ConcurrentQueue is only ensuring that calls to methods of that class are observed to be atomic; it is making no other guarantees surrounding thread safety.