Using AddOrUpdate method in ConcurrentDictionary in .NET 4.0 [closed]
Asked Answered
L

1

7

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..

Ludwog answered 3/1, 2011 at 11:44 Comment(3)
Which troubles are you facing? Any error messages?Siberson
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..Ludwog
You have "problems using a specific tool". But without any info on what you want to accomplish (and why) there can't be a good answer. Voting NARQ.Apterygial
F
30

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);
Fluted answered 3/1, 2011 at 13:48 Comment(1)
AddOrUpdate method is not atomic. updateValueFactory delegate is outside of the lock. So, it's possible to have race conditions. You can check msdn documentation of AddOrUpdate.Infatuate

© 2022 - 2024 — McMap. All rights reserved.