JokingBear
JokingBear

Reputation: 39

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.

Upvotes: 1

Views: 2965

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727057

[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)
);

Upvotes: 4

Related Questions