16

跟踪以下进度的最佳方法是什么

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(当前/总计),但我不想使用任何会对并行性产生不利影响的东西。

4

3 回答 3

15

Jon 的解决方案很好,如果你需要像这样简单的同步,你的第一次尝试应该几乎总是使用lock. 但是,如果您测量到锁定使事情变得太慢,您应该考虑使用类似Interlocked.

在这种情况下,我将使用Interlocked.Increment增加当前计数,并更改Progress为一个属性:

private long total;
private long current;
public double Progress
{
    get
    {
        if (total == 0)
            return 0;
        return (double)current / total;
    }
}

…

this.total = Products.LongCount();
this.current = 0;

Parallel.ForEach(Products, product =>
{
    try
    {
        var price = GetPrice(SystemAccount, product);
        SavePrice(product, price);
    }
    finally
    {
        Interlocked.Increment(ref this.current);
    }
});

此外,您可能想考虑如何处理异常,我不确定以异常结束的迭代是否应该算作完成。

于 2013-01-26T13:01:03.767 回答
4

由于您只是在进行一些快速计算,因此请通过锁定适当的对象来确保原子性:

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;
        }
    }});
于 2013-01-26T12:05:59.450 回答
2

在体内不使用任何阻塞的解决方案:

long total = Products.LongCount();
BlockingCollection<MyState> states = new BlockingCollection<MyState>();

Parallel.ForEach(Products, () =>
{
    MyState myState = new MyState();
    states.Add(myState);
    return myState;
},
(i, state, arg3, myState) =>
{
    try
    {
        var price = GetPrice(SystemAccount, product);
        SavePrice(product,price);
    }
    finally
    {
        myState.value++;
        return myState;
    }
},
i => { }
);

然后,访问当前进度:

(float)states.Sum(state => state.value) / total
于 2013-01-26T12:13:01.320 回答