Trauer
Trauer

Reputation: 2091

Is Dictionary<TKey,TValue>.Item[TKey] Property thread safe to set, if key is already in the dictionary?

Before anything, I already read this and I don't think it answers my question.

I'm writing a method to update the values of a dictionary. I will not insert nor remove any keys.

I plan to do this:

private static void Example(Dictionary<Individual, float> dict) {
            var keys = dict.Keys.ToArray();

            Parallel.For(0, keys.Length, i => {
                var key = keys[i];
                var newValue = DoHardMath(key);
                dict[key] = newValue;
            });         
        }

Is this thread-safe? The documentation doesn't make this clear.

Upvotes: 1

Views: 69

Answers (1)

tmaj
tmaj

Reputation: 34987

Your question is very specific, but ConcurrentDictionary would avoid the anxiety.

Docos at:

Upvotes: 2

Related Questions