liveBook · Manning

TryAdd

As explained in C# Concurrency: Asynchronous and multithreaded programming

TryAdd is a ConcurrentDictionary method that conditionally inserts a key-value pair and returns false when the key already exists.

TryAdd conditionally inserts a key-value pair into a ConcurrentDictionary. It treats an existing key as normal contention: insertion succeeds normally, or returns false instead of throwing an exception. section 13.2.1

Replacing Add with TryAdd removes the exception caused by a competing insertion, but a TryGetValue-then-TryAdd sequence can still create separate copies of the same item on multiple threads. section 13.2.1

Use the result and choose the operation according to the concurrency requirement:

  • Check the Boolean result when the caller must know whether insertion won the race. section 13.2.1
  • Prefer GetOrAdd when lookup and initialization must be combined into one operation that avoids duplicate item copies. section 13.2.1
  • Do not confuse this overload with BlockingCollection<T>.TryAdd, which waits for capacity up to a timeout and returns false when the timeout expires. section 13.2.2

Thread-safe cache insertion

if (!dictionary.TryGetValue(itemId, out var item)) { item = CreateAndInitializeItem(itemId); dictionary.TryAdd(itemId, item); } This prevents an insertion exception, although concurrent callers can still initialize separate item instances. section 13.2.1

Listing 13.8 Thread-safe cache with ConcurrentDictionary.GetOrAdd
var item = dictionary.GetOrAdd(itemId,CreateAndInitializeItem);

Compare the TryAdd cache pattern with GetOrAdd’s single-line combined operation. section 13.2.1

How C# Concurrency: Asynchronous and multithreaded programming covers it

How deep it goes
Explains collision semantics and duplicate initialization, then stops short of implementing the stronger GetOrAdd alternative.
Examples
Uses a concurrent cache example and contrasts it with GetOrAdd and timeout-based BlockingCollection insertion.
What it assumes
Assumes awareness of dictionary lookup, insertion, and multithreaded races while teaching collision handling through TryAdd.
What you can do after
Apply it via ConcurrentDictionary to perform conditional insertion without treating an existing key as an exception.
How it connects
Connects TryAdd with ConcurrentDictionary, TryGetValue, Add, GetOrAdd, and BlockingCollection.

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.