Reputation: 6988
Inside my web api controller I'm looping over a list with Parallel.ForEach(). I have a counter that I increment in the Parallel.ForEach code. I'm noticing that counter is a variable number each time I run it and it's never as high as the list I'm looping over with Parallel.ForEach(). It seems like Parallel.ForEach() isn't waiting to come back before it's finished with looping over all elements.
// get all the new records from the csv
var newData = csv.GetRecords<MyEFTable>().ToArray();
int count = 0;
Parallel.ForEach(newData, (d) => {
count++});
newData has 6588 items and count generally is around 3400 or so items but again it's variable each time. This is very strange.
Upvotes: 0
Views: 663
Reputation:
You're getting into a race condition. You need to use var newCount = Interlocked.Increment(ref count);
to safely increment a variable in a multithreaded environment. The newCount
variable is the incremented counter.
The reason this happens is because count++
is not atomic. It's actually three operations: getting the value, adding 1, then storing it back. If you have those three things happening concurrently, stuff gets out of order and wonky.
When dealing with threads, its vital to ensure each thread isn't manipulating the same data, or they will squash each other.
Upvotes: 6