Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConcurrentDictionary enumeration and locking

If I have a ConcurrentDictionary, do I need to lock it when looping thru it using foreach?

like image 599
Schultz9999 Avatar asked Sep 04 '12 17:09

Schultz9999


People also ask

Does ConcurrentDictionary need lock?

ConcurrentDictionary<TKey,TValue> is designed for multithreaded scenarios. You do not have to use locks in your code to add or remove items from the collection. However, it is always possible for one thread to retrieve a value, and another thread to immediately update the collection by giving the same key a new value.

What is the purpose of the ConcurrentDictionary?

ConcurrentDictionary is thread-safe collection class to store key/value pairs. It internally uses locking to provide you a thread-safe class. It provides different methods as compared to Dictionary class. We can use TryAdd, TryUpdate, TryRemove, and TryGetValue to do CRUD operations on ConcurrentDictionary.

Is ConcurrentDictionary slow?

In . Net 4, ConcurrentDictionary utilized very poor locking management and contention resolution that made it extremely slow. Dictionary with custom locking and/or even TestAndSet usage to COW the whole dictionary was faster.

Is ConcurrentDictionary indexer thread-safe?

It is thread-safe in the sense that the internal state of the ConcurrentDictionary will not be corrupted. This is the main guarantee offered by this class.


1 Answers

If I have a ConcurrentDictionary, do I need to lock it when looping thru it using foreach?

No. From the docs for ConcurrentDictionary.GetEnumerator:

The enumerator returned from the dictionary is safe to use concurrently with reads and writes to the dictionary, however it does not represent a moment-in-time snapshot of the dictionary. The contents exposed through the enumerator may contain modifications made to the dictionary after GetEnumerator was called.

As long as you're okay with that, you don't need any kind of locking.

like image 147
Jon Skeet Avatar answered Oct 02 '22 07:10

Jon Skeet