Using a thread-safe dictionary in .NET C# Part 1: introduction
July 28, 2015 1 Comment
In this post we saw how to use the thread-safe counterpart of the Queue object, i.e. the ConcurrentQueue of T. The standard Dictionary class also has a thread-safe counterpart and it’s called ConcurrentDictionary which resides int the System.Collections.Concurrent namespace.
The ConcurrentDictionary is definitely a dictionary type but it can mimic other collection types if you need a thread-safe collection that doesn’t have a built-in concurrent counterpart such as a List. ConcurrentDictionary is more difficult to use than a standard dictionary so its usage cannot really be summarised in a single short post. Therefore we’ll go through the basics in a mini-series instead.
It implements the IDictionary interface just like Dictionary but some methods are hidden:
- Add: the standard Add method throws an exception if the provided key already exists. In a multi-threaded environment when different threads are reading from and writing to the same shared dictionary it’s difficult to know whether a key has been added by an other thread. Hence the usage of the Add method is discouraged in a ConcurrentDictionary
- Remove: the problem is the same as with the Add method but appears when an item is removed from the dictionary
- ConcurrentDictionary doesn’t allow the same content initialiser when constructing it
This last point means that the following initialisation…
Dictionary<string, int> movies = new Dictionary<string, int>() { {"Horror", 5}, {"Action", 10} };
…will fail for a ConcurrentDictionary:
ConcurrentDictionary<string, int> movieCategoriesOnstock = new ConcurrentDictionary<string, int>() { {"Horror", 5}, {"Action", 10} };
..with the exception saying that the ConcurrentDictionary doesn’t contain a definition for the Add method.
There are other methods that let you add, remove or update a key-value pair in a concurrent dictionary. We’ll continue with some of them in the next post.
View the list of posts on the Task Parallel Library here.
Pingback: Summary of thread-safe collections in .NET – .NET training with Jead