TryUpdate prevents one thread from overwriting another thread’s change by replacing a dictionary value only when it still equals an expected previous value. section 13.2.1
A read-increment-write sequence contains a race: two threads can read 1, both calculate 2, and lose one increment. TryUpdate detects that intervening change. section 13.2.1
Retrying an increment
Read the current value into prevValue, then call TryUpdate(key, prevValue + 1, prevValue). Break when it returns true; otherwise, retry with the newly observed value. section 13.2.1
Listing 13.10 Thread-safe increment with ConcurrentDictionary.TryUpdate
private ConcurrentDictionary<string, int> _dictionary = new();
public void Increment(string key)
{
while(true)
{
int prevValue = _dictionary[key];
if(_dictionary.TryUpdate(key, prevValue+1, prevValue))
break;
}
}
Runnable C# listing showing a ConcurrentDictionary increment implemented with a TryUpdate retry loop. section 13.2.1
