Using the AddOrUpdate Method in ConcurrentDictionary in .NET 4.0

I am encountering problems in parallel collections and threads, in particular, using the AddOrUpdate method in ConcurrentDictionary basically ..... I cannot use it. I could not find a good example ... and also could not fully understand the ConcurrentQueue example in the MSDN programming guide ..


The AddOrUpdate method in ConcurrentDictionary is basically ..... I can't use it. I could not find good examples on it ... and also could not fully understand the ConcurrentQueue example in the MSDN programming guide ..

+6
c # concurrent-collections
source share
1 answer

In a regular dictionary, you can see the following code:

Dictionary<string, int> dictionary = GetDictionary(); if (dictionary.ContainsKey("MyKey")) { dictionary["MyKey"] += 5; } else { dictionary.Add("MyKey", 5); } 

This is unsafe code. There are several race conditions: "MyKey" can be added / removed after calling ContainsKey , and the value (if any) associated with "MyKey" can be changed between reading and assignment in a row using the += operator.

The AddOrUpdate method AddOrUpdate designed to fix these streaming issues by providing a mechanism for adding or updating the value associated with a given key, depending on the key. It is similar to TryGetValue in that it combines several operations (in this case, checking the key and either inserting or changing the value depending on the presence of the specified key) into one effective atomic action that is not subject to race conditions.

To make this specific, here is how you could fix the above code using AddOrUpdate :

 ConcurrentDictionary<string, int> dictionary = GetDictionary(); // Either insert the key "MyKey" with the value 5 or, // if "MyKey" is already present, increase its value by 5. dictionary.AddOrUpdate("MyKey", 5, (s, i) => i + 5); 
+28
source share

All Articles