Developer knowledge network ยท moderated exchange

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Knowledge indexLive
4Categories
919Threads
2.8KPosts
Tutorial

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

cpp_concurrency_guru
C++ Standards Expert
MEMBER
Rep: 47
Join Date: Feb 2018
Posts: 17
Thanks: 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
Rep: 103
Join Date: Apr 2018
Posts: 40
Thanks: 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
Rep: 57
Join Date: Mar 2019
Posts: 18
Thanks: 40
1 months ago ยท Jul 4, 2026 7:59 PM
#3

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