liveBook · Manning

ConcurrentDictionary<TKey,TValue>.TryUpdate

As explained in C# Concurrency: Asynchronous and multithreaded programming

TryUpdate is a ConcurrentDictionary method that replaces a value only when its current value matches an expected value.

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

How C# Concurrency: Asynchronous and multithreaded programming covers it

How deep it goes
Explains the race sequence and retry-loop mechanism, but does not measure performance or compare implementation costs.
Examples
Uses a string-keyed integer dictionary and a concurrent increment that retries until TryUpdate succeeds.
What it assumes
Assumes familiarity with dictionary reads and writes, while demonstrating the read-modify-write race from the increment example.
What you can do after
Apply it via ConcurrentDictionary by implementing a retrying, conditional update for concurrent increments.
How it connects
Connects ConcurrentDictionary with race conditions, locking, TryGetValue, TryAdd, GetOrAdd, and atomic update attempts.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C# Concurrency: Asynchronous and multithreaded programming. The section links point to the parts of the book it draws on.