Developer knowledge network · moderated exchange

مجتمع الكود غير الموثوق به

أبحاث المطورين، مجتمع الهندسة العكسية والترميز

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 months ago · 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 months ago · 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 months ago · Jul 4, 2026 7:59 PM
#3

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