Developer knowledge network · moderated exchange

UnreliableCode 커뮤니티

개발자 연구, 리버스 엔지니어링 및 코딩 커뮤니티

Knowledge index살다
4Categories
919Threads
2.8K게시물
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.