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);