Skip to content

ConcurrentDictionary.GetOrAdd method executes given valueFactory concurrently #62919

@tonyhicks20

Description

@tonyhicks20

Description

As title states, the GetOrAdd(string key, Func valueFactory) method on the System.Collections.Concurrent.ConcurrentDictionary class calls the valueFactory multiple times.

Reproduction Steps

using System.Collections.Concurrent;

ConcurrentDictionary<string, int> dictionary = new ConcurrentDictionary<string, int>();

int count = 0;

await Task.WhenAll(
    Enumerable.Range(0, 10000)
    .Select(x => Task.Factory.StartNew(
      () => dictionary.GetOrAdd("mykey", _ => Interlocked.Increment(ref count)))
    )
);

if (count != 1)
  Console.WriteLine("This number should only be 1, but it's " + count);
else
  Console.WriteLine("Number is correct");
Console.ReadLine();

Expected behavior

I expect the value factory to only be called once.

Actual behavior

The value factory is called multiple times.

Regression?

.NET framework seems fine

Known Workarounds

No response

Configuration

The current version of .NET is 6, I tried this on 5 too and I get the same incorrect behaviour.
OS is Windows 10 - 19042.610
x64

I don't know if this is specific to this configuration but I doubt it since this works fine with .NET framework

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions