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);
Dan tao
source share