Thread-Safety Dictionary Update

Is the following code stream safe?

var dict = new Dictionary<int, string>()
    { { 0, "" }, { 1, "" }, { 2, "" }, { 3, "" } };

var nums = dict.Keys.ToList();

Parallel.ForEach(nums, num =>
            {
                dict[num] = LongTaskToGenerateString();
            });

return dict;
+4
source share
3 answers

No, the Dictionary<TKey, TValue>class is not thread safe for modification, as shown in the documentation :

A Dictionary<TKey, TValue> , . , . , , . , .

, LongTaskToGenerateString, .

SyncRoot , ConcurrentDictionary<TKey, TValue>, asawyer .

, , ( this) - version. , , . .

+5

, . , .

, PLINQ :

var nums = new[] { 0, 1, 2, 3 };

var dict = nums.AsParallel()
               .Select(num => new KeyValuePair<int, string>
                                  (num, LongTaskToGenerateString(num)));
               .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

return dict;
+3

All Articles