You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
GetOrCreate on a ConcurrentDictionary held as IDictionary<,> throws ArgumentException ("same key has already been added") when two callers race on a missing key #194
#134 fixed the GetOrCreate race by adding ConcurrentDictionary<TKey,TVal> overloads. C# picks an overload from the declared type at compile time, though. A ConcurrentDictionary stored in a field, property or parameter typed IDictionary<TKey,TVal> still binds to the IDictionary overloads, which do TryGetValue followed by Add:
When two threads both miss, the second IDictionary.Add on the ConcurrentDictionary throws ArgumentException: An item with the same key has already been added. #134 named "have the IDictionary path detect ConcurrentDictionary" as an option, but that part was never done.
Repro
I ran 2000 iterations, each starting 8 tasks released together by a Barrier, against Extensions.csproj for net10.0:
IDictionary<int,List<int>>d=newConcurrentDictionary<int,List<int>>();d.GetOrCreate(1);// 5 ArgumentExceptions in 2000 iterationsIDictionary<int,string>d2=newConcurrentDictionary<int,string>();d2.GetOrCreate(1,"v");// 1 ArgumentException in 2000 iterations
Expected: no exception, and every caller gets the single stored value. This is what the concrete-typed overload already guarantees.
Actual: an intermittent ArgumentException.
Why it matters
Code is commonly written against IDictionary<,> and handed a ConcurrentDictionary because it is shared across threads. That caller gets the unsafe path without any warning, and it fails only under load.
Suggested fix / acceptance criteria
In both IDictionary overloads, check if (dictionary is ConcurrentDictionary<TKey, TVal> concurrent) and delegate to concurrent.GetOrAdd(key, static _ => new TVal()) or concurrent.GetOrAdd(key, defaultValue). The simplest route is to call the existing concurrent overloads.
Add a Parallel.For stress test that goes through an IDictionary-typed reference, for both overloads. It should assert that no exception is thrown and that every caller receives the same instance.
Activity