Dictionary Thread Safety when updating keys in different threads

13 views Asked by At

I have a very specific use case where I need to update each key of a dictionary with a value I will have available from another dictionary in the same method context.

While I know that dictionaries are in general not considered thread safe, I was wondering if they can be considered thread safe if you are certain no two keys can be updated at the same time.

The scenario will boil down to something similar to the xunit test below, which I churned for a good hour without failures.

[Theory]
[InlineData(10000)]
[InlineData(100000)]
[InlineData(1000000)]
[InlineData(10000000)]
public void Transform(int a)
{
    var nums = Enumerable.Range(1, a).ToDictionary(i => i);
    foreach (var num in nums.Keys.AsParallel())
    {
        nums[num] = num * num;
        Assert.True(num > 0);
    }
}
1

There are 1 answers

0
The Karan Pargaien On

If you are in search for thread safe dictionary implementation. You have an built-in solution: ConcurrentDictionary.

Read more: https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentdictionary-2?view=net-8.0