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.