Skip to content

GetOrCreate on a ConcurrentDictionary held as IDictionary<,> throws ArgumentException ("same key has already been added") when two callers race on a missing key #194

Closed

Description

@matt-edmondson

What's wrong

#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 = new ConcurrentDictionary<int, List<int>>();
d.GetOrCreate(1);          // 5 ArgumentExceptions in 2000 iterations
IDictionary<int, string> d2 = new ConcurrentDictionary<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

  1. added
    bug
    on Nov 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions