2

In the below code am using Parallel.ForEach to get the data of each item in my collection and store the response in the dictionary. But, in the dictionary the key and values are mismatched. Response of 1st item, is stored in the name of 2nd Item or 3rd item name.

Dictionary<string, object> keyValues = new Dictionary<string, object>();
Parallel.ForEach(myCollection, item =>
{
    var data = GetData(item);
    if (!keyValues.ContainsKey(item))
    {
        keyValues.Add(item, data);
    }
});
return keyValues;
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Beginner
  • 193
  • 1
  • 8
  • 3
    `Dictionary.Add` is not thread-safe. You could use a `ConcurrentDictionary`, or just use a standard `foreach`. Is `GetData` computationally expensive enough to warrant multithreading? – Johnathan Barclay Mar 08 '22 at 10:53
  • 1
    Did you mean `if (!keyValues.ContainsKey(item))`? Regardless, `ConcurrentDictionary` has `GetOrAdd` or `TryAdd` methods. – Andrew McClement Mar 08 '22 at 10:55

1 Answers1

2

Try to use ConcurrentDictionary, because Dictionary isn't thread-safe.

Replace the ContainsKey and Add method calls with TryAdd

Radovancev
  • 286
  • 3
  • 11