Search code examples
c#multithreadingparallel.foreach

Parallel.ForEach and Dictionary collection results in null key


I don't understand how my code went wrong here's a code piece:

var filter = new Dictionary<string, Dictionary<string,bool>>();
//data here is of type Dictionary<string,bool>
Parallel.ForEach(data, t =>
{
    var filter1 = data.Where(p => p.Value).ToDictionary(p => p.Key, p => p.Value);
    filter.Add(t.key, filter1);
});

Sometimes, the final filter has a null key in it, which has never happened if I had used a simple for loop.


Solution

  • [this] has never happened if I had used a simple for loop.

    The problem is that you are adding to filter concurrently. You could fix this by using AsParallel():

    var filter = data.AsParallel().ToDictionary(t =>
        t.Key
    ,   data.Where(p=>p.Value).ToDictionary(p=>p.Key, p=>p.Value)
    );