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.
count++is not thread safe. Replace it withInterlocked.Incremenet(ref count)