If i use ConcurentDictionary dic in multithread accessed method can i be sure that in such construction:

foreach (Subscription sub in subscriptions[ex].Values)
                    {
                      ....
                    }

subscriptions is ConcurrentDictionary<string, ConcurrentDictionary<long, Subscription>> wont change when running by several methods, so that it will be thread save? Or should i use lock like:

lock(padLock)
{   
foreach (Subscription sub in subscriptions[ex].Values)
                        {
                          ....
                        }
}

to make it work properly?

有帮助吗?

解决方案

All public and protected members of ConcurrentDictionary are thread-safe and may be used concurrently from multiple threads.

So yes, you will be safe without an extra lock, even if some other thread modifies the Values collection while you're iterating over it.

By modifies I mean that it adds new pairs or changes existing values in the dictionary.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top