Pregunta

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?

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top