Search code examples
c#multithreadingdictionaryconcurrentdictionaryimmutable-collections

What's the difference between a ConcurrentDictionary and an ImmutableDictionary?


I am reading Concurrency in C# Cookbook and the book told me that:

ConcurrentDictionary<TKey, TValue> is best when you have multiple threads reading and writing to a shared collection. If the updates are not constant (if they’re more rare), than ImmutableDictionary<TKey,TValue> may be a better choice.

I know that Add or Remove a large immutable collection can be slow, and my question is, is there any other difference between them? Now that they are all thread safe, why is ImmutableDictionary a better choice when the updates are not constant?


Solution

  • These two classes ConcurrentDictionary and ImmutableDictionary were compared just because of the simple reason, both are thread safe.

    However, it is not a good idea to use ImmutableDictionary for multi-threading. It is designed to represent data which should be loaded once, and shouldn't be changed / modified later on. Any modifications would lead to creating new instance of ImmutableDictionary, which is not really efficient.