I'm using a concurrent dictionary to store about two million records and want to know what to initialize the concurrency level of my dictionary to.
The MSDN page has the following comment in its example code:
The higher the
concurrencyLevel
, the higher the theoretical number of operations that could be performed concurrently on theConcurrentDictionary
. However, global operations like resizing the dictionary take longer as theconcurrencyLevel
rises.
This is the best I could find that explains what the concurrencyLevel means and yet it is still very vague.
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.
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.
ConcurrentDictionary is a generic collection, ConcurrentDictionary was introduced in . NET framework 4.0 as it is available in System. Collections. Concurrent namespace, this generic collection is used in the case of a multi-threaded application.
The most important thing to understand is that even if you have more concurrent accesses than the concurrencyLevel
, operations will still be thread-safe. That is, setting concurrencyLevel
is a matter of performance, not correctness.
concurrencyLevel
specifies the number of independent locks which are available for map operations. If you have n
threads concurrently accessing the dictionary, setting concurrencyLevel
higher than n
will not yield any additional benefit. In general, the optimal value for concurrencyLevel
will be significantly lower than the number of worker threads, though, since a given worker won't spend the majority of its time accessing the dictionary.
Profiling your application is really the only way to determine the optimal concurrencyLevel
. Setting it to the expected number of worker threads is a good start, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With