跟踪以下进度的最佳方法是什么?
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);
}});我希望将进度变量从0.0更新为1.0 (当前/总),但我不希望使用任何会对并行度产生不利影响的内容。
发布于 2013-01-26 20:05:59
由于您只是执行一些快速计算,因此通过锁定适当的对象来确保原子性:
long total = Products.LongCount();
long current = 0;
double Progress = 0.0;
var lockTarget = new object();
Parallel.ForEach(Products, product =>
{
try
{
var price = GetPrice(SystemAccount, product);
SavePrice(product,price);
}
finally
{
lock (lockTarget) {
Progress = ++this.current / total;
}
}});https://stackoverflow.com/questions/14536656
复制相似问题