Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to chose concurrency level of a concurrent dictionary

Tags:

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 the ConcurrentDictionary. However, global operations like resizing the dictionary take longer as the concurrencyLevel rises.

This is the best I could find that explains what the concurrencyLevel means and yet it is still very vague.

like image 549
Michael Smale Avatar asked May 07 '15 21:05

Michael Smale


People also ask

Do you need to lock concurrent Dictionary?

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.

How does concurrent Dictionary work?

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.

What is concurrent Dictionary in C#?

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.


1 Answers

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.

like image 91
Sneftel Avatar answered Oct 12 '22 19:10

Sneftel