I have a Parallel.ForEach() loop that takes a list of URL's and downloads each of them for some additional processing. Outside my loop I have declared a loop counter variable and inside the loop body I use Interlocked.Increment() thinking this would be the best way to keep a "thread safe" way of increasing the count as each loop interation is performed.
int counter = 0;
Parallel.ForEach(urlList, (url, state) =>
{
// various code statments
Interlocked.Increment( ref counter );
Debug.WriteLine(" ......... counter: " + counter);
});
I would have thought that I would see something similar to:
......... 1
......... 2
......... 3
......... 4
......... 5
.........
.........
......... n
But what I get instead is 16 " ......... 0" (this is because I have a dual quad core computer with 8 native cores, but hyper threading is enabled giving me a total of 16 cores). Then I will start to see the counter get incremented normally for the most part but sometimes I will see duplicate or even triplicate counter values in the Debug output.
Using a Parallel.ForEach() what is the best way to count loop iterations? Thanks for any advice.