liveBook · Manning

GetOrAdd

As explained in C# Concurrency: Asynchronous and multithreaded programming

GetOrAdd is an ImmutableInterlocked operation that returns an existing value or adds and returns a value for a missing key in an immutable dictionary.

GetOrAdd combines lookup and insertion for a thread-safe cache. It returns the existing value for a key or creates and adds one when the key is missing. section 13.2.1

The delegate overload can execute initialization more than once when threads race. Only one result is stored, and competing callers receive the same published object. Keep initialization repeatable, or account for cleanup when discarded objects have resources. section 13.2.1

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

Use the delegate overload to replace a separate TryGetValue, construction, and TryAdd sequence with one cache operation. section 13.2.1

How C# Concurrency: Asynchronous and multithreaded programming covers it

How deep it goes
Explains lookup, insertion, delegate execution, fine-grained locking, and repeated initialization, but stops short of implementation internals.
Examples
Shows a cache factory delegate and contrasts separate lookup-plus-insertion code with GetOrAdd.
What it assumes
Assumes familiarity with dictionaries, delegates, and concurrent access; distinguishes TryAdd from atomic combined lookup and insertion.
What you can do after
Apply it via ConcurrentDictionary.GetOrAdd to simplify concurrent cache initialization and review factory repeatability.
How it connects
Connects GetOrAdd with ConcurrentDictionary, TryGetValue, TryAdd, cache initialization, and fine-grained locking.

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.