Search code examples
c#multithreadingproducer-consumerconcurrentdictionaryblockingcollection

ConcurrentDictionary used by 3 threads


I have a class that uses a ConcurrentDictionary.

In this class, there are three functions that perform some operations on this ConcurrentDictionnary.

Each function is called by a different thread.

  • First function operations : dictionnary.Where, dictionnary.TryRemove
  • Second function operations : dictionnary.Where
  • Third function operations : dictionnary.TryAdd

while (!dictionnaryKey.TryAdd(key, item))
{
  LogWriter.error_log("try add to dictionnary ...");
}

This last function blocks at different times. I have to add my element to the dictionary without blocking, but how can I do?


Solution

  • I have to add my element to the dictionary without blocking, but how can I do?

    That is not possible. The ConcurrentDictionary is optimized for multi-threading and low-contention, but that still doesn't mean there is no contention (blocking). All the write operations in a ConcurrentDictionary use a fine-grained-locking model, and multiple lock objects are used internally to sync the write operations to keep the data consistent and prevent multi-threading exceptions.

    Your TryAdd method is evidently blocked because it is waiting for a lock (acquired by a different thread) to get released.

    The reason why Concurrent dictionary enumerations (e.g. your Where operations) are not blocking is because they use a lock-free model.

    Using a plain old dictionary instead of the ConcurrentDictionary would not yield any performance benefits, because you would have to handle the locking yourself using read-write locks.

    As @Usr said in your comments, if your goal is to have non-blocking processing than your whole concept of using a single ConcurrentDictionary in your multiple-writers scenario might be wrong.