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

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
Cheshta
  • 71
  • 1
  • 1
  • 2
  • Which troubles are you facing? Any error messages? – Uwe Keim Jan 03 '11 at 11:45
  • 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.. – Cheshta Jan 03 '11 at 11:55
  • 1
    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. – H H Jan 03 '11 at 13:01

1 Answers1

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);
Dan Tao
  • 125,917
  • 54
  • 300
  • 447
  • 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. – Y.Doktur Dec 04 '18 at 12:19