When should I use ConcurrentDictionary and Dictionary?

“Use ConcurrentDictionary if you use your dictionary in a lot in code” is kind of vague advice. I don’t blame you for the confusion. ConcurrentDictionary is primarily for use in an environment where you’re updating the dictionary from multiple threads (or async tasks). You can use a standard Dictionary from as much code as you … Read more

How to achieve remove_if functionality in .NET ConcurrentDictionary

.NET doesn’t expose a RemoveIf directly, but it does expose the building blocks necessary to make it work without doing your own locking. ConcurrentDictionary implements ICollection<T>, which has a Remove that takes and tests for a full KeyValuePair instead of just a key. Despite being hidden, this Remove is still thread-safe and we’ll use it … Read more

ConcurrentDictionary GetOrAdd async

GetOrAdd won’t become an asynchronous operation because accessing the value of a dictionary isn’t a long running operation. What you can do however is simply store tasks in the dictionary, rather than the materialized result. Anyone needing the results can then await that task. However, you also need to ensure that the operation is only … Read more

.NET – Dictionary locking vs. ConcurrentDictionary

A thread-safe collection vs. a non-threadsafe-collection can be looked upon in a different way. Consider a store with no clerk, except at checkout. You have a ton of problems if people don’t act responsibly. For instance, let’s say a customer takes a can from a pyramid-can while a clerk is currently building the pyramid, all … Read more