How can I increment an integer value outside the scope of a parallel.foreach loop? What\'s is the lightest way to synchronize access to objects outside parallel loops?
Parallel.Foreach comes along with an extra overload that perfectly fits for that kind of scenario when you just want to count things inside the loop.
int totalCount = 0;
Parallel.ForEach(files, () => 0, (file, loopState, localCount) =>
{
if(ProcessFile(file))
localCount++;
return localCount;
}, localCount => Interlocked.Add(ref totalCount, localCount));
Console.WriteLine($"Processed {totalCount}/{files.Length} files.");
Into the loop body you can inject a thread local count varialble and increment/decrement it as usual. This way you do not have an InterLocked call in every loop cycle. Instead there is just one Interlocked.Add call at the end of each parallel Task summing up totalCount.
Note that with this method you should not use totalCount
from within the loop body. If your problem requires to access totalCount from within the loop body you have to use the InterLocked.Incerment method as describe in other answers.