Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using AddOrUpdate method in ConcurrentDictionary in .NET 4.0 [closed]

I am facing troubles in Concurrent collections and threading, specifically using the AddOrUpdate method in ConcurrentDictionary basically..... I am not able to put it into use.. I couldn't find any good example on it... and also couldn't understand fully, the example of ConcurrentQueue in MSDN programming guide..


AddOrUpdate method in ConcurrentDictionary basically..... I am not able to put it into use.. I couldn't find any good example on it... and also couldn't understand fully, the example of ConcurrentQueue in MSDN programming guide..

like image 904
Cheshta Avatar asked Jan 03 '11 11:01

Cheshta


1 Answers

In a regular dictionary, you might see code like this:

Dictionary<string, int> dictionary = GetDictionary();

if (dictionary.ContainsKey("MyKey"))
{
    dictionary["MyKey"] += 5;
}
else
{
    dictionary.Add("MyKey", 5);
}

This is not thread-safe code. There are multiple race conditions: "MyKey" may be added/removed after the call to ContainsKey, and the value (if any) associated with "MyKey" may be changed between read and assignment in the line using the += operator.

The AddOrUpdate method is intended to resolve these threading issues by providing a mechanism to add or update the value associated with a given key, depending on whether the key is present. It is similar to TryGetValue in that it combines multiple operations (in this case, checking for a key, and either inserting or modifying a value depending on the presence of said key) into one effectively atomic action not susceptible to race conditions.

Just to make this concrete, here is how you would 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);
like image 178
Dan Tao Avatar answered Nov 12 '22 02:11

Dan Tao