Developer knowledge network · moderated exchange

Сообщество UnreliableCode

Сообщество разработчиков, обратного проектирования и кодирования

Tutorial

Pitfalls of ConcurrentDictionary.GetOrAdd: Why the factory delegate can execute multiple times [StackOverflow Architecture Guide]

cpp_concurrency_guru
C++ Standards Expert
MEMBER
Представитель: 47
Дата присоединения: Feb 2018
Сообщения: 17
Спасибо: 75
1 месяцев назад · Jul 4, 2026 11:14 AM
#1

A subtle concurrency trap in ConcurrentDictionary<TKey, TValue>:

GetOrAdd(key, valueFactory) guarantees that only one single instance is stored in the dictionary. However, under high thread contention, the valueFactory delegate may be invoked multiple times concurrently!

If your factory opens a database connection or creates expensive resources, use Lazy<T>:

CSHARP
var item = dict.GetOrAdd(key, k => new Lazy<ExpensiveResource>(() => new ExpensiveResource(k))).Value;

Lazy<T> guarantees that the constructor executes exactly once across all competing threads!

dotnet_runtime_architect
.NET Core Specialist
MEMBER
Представитель: 103
Дата присоединения: Apr 2018
Сообщения: 40
Спасибо: 24
1 месяцев назад · Jul 4, 2026 3:35 PM
#2

This is one of the most common concurrency interview questions and production bugs in .NET backends.

csharp_async_master
Async & Task Expert
MEMBER
Представитель: 57
Дата присоединения: Mar 2019
Сообщения: 18
Спасибо: 40
1 месяцев назад · Jul 4, 2026 7:59 PM
#3

The Lazy<T> wrapper pattern guarantees thread-safe single initialization.