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;
No, the Dictionary<TKey, TValue>class is not thread safe for modification, as shown in the documentation :
Dictionary<TKey, TValue>
A Dictionary<TKey, TValue> , . , . , , . , .
, LongTaskToGenerateString, .
LongTaskToGenerateString
SyncRoot , ConcurrentDictionary<TKey, TValue>, asawyer .
SyncRoot
ConcurrentDictionary<TKey, TValue>
, , ( this) - version. , , . .
version
, . , .
, 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;
, ConcurrentDictionary