【问题标题】:Progress update in Parallel.For() loopsParallel.For() 循环中的进度更新
【发布时间】:2010-10-21 09:29:28
【问题描述】:

您可以猜到 Parallel.For() 循环的索引从一个值跳转到另一个值。如何估算完成的工作量?

谢谢。

【问题讨论】:

    标签: .net parallel-extensions


    【解决方案1】:

    通过保留计数器而不是查看索引?例如:

    int counter  = 0;
    Parallel.For(4, 500, i => {
        // TODO: something useful...         
        int progress = Interlocked.Increment(ref counter);
        Console.WriteLine("{0}: {1}", progress, i);
    });
    

    (Interlocked 的用法对于避免在访问 counter 时出现竞争条件至关重要)

    【讨论】:

    • 和here 是一样的包装。
    【解决方案2】:
    int progress = 0;
    Parallel.For( from, to, i => {
    // do the job
    Interlocked.Increment(ref progress);
    });
    

    现在实际进度是(float)(to - from) / progress

    【讨论】:

    • 在不干扰线程同步的情况下没有办法获取这个值?
    • @devdept 没有。但是使用这种方法有什么问题?
    • 我认为 Parallel.For() 包含一种更优雅的方式来获取此值。
    • @devdept 你要加两行代码,这里有什么不优雅的地方?
    • @Alberto, here 是一个封装线程东西的包装器。不过,使用“增量”返回的值很重要,否则您可能仍会遇到竞争条件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    相关资源
    最近更新 更多