What is the best way way to track progress in the following
long total = Products.LongCount();
long current = 0;
double Progress = 0.0;
Parallel.ForEach(Products, product =>
{
try
{
var price = GetPrice(SystemAccount, product);
SavePrice(product,price);
}
finally
{
Interlocked.Decrement(ref this.current);
}});
I want to update the progress variable from 0.0 to 1.0 (current/total) but i don't want to use anything that would have an adverse effect on the parallelism.
Since you are just doing a few quick calculations, ensure atomicity by locking on an appropriate object:
Jon's solution is good, if you need simple synchronization like this, your first attempt should almost always use
lock
. But if you measure that the locking slows things too much, you should think about using something likeInterlocked
.In this case, I would use
Interlocked.Increment
to increment the current count, and changeProgress
into a property:Also, you might want to consider what to do with exceptions, I'm not sure that iterations that ended with an exception should be counted as done.
A solution without using any blocking in the body:
Then, to access the current progress: