Parallel.For属性

时间:2012-10-11 11:42:24

标签: c# multithreading task-parallel-library

public static void Main (string[] args)
        {
            int k = 0;
            int i = 3;
            var loopRes = Parallel.For (0, 20, (J) =>
            {
                k = i / J;
                Console.WriteLine ("Result After division " + J + " = " + k);
            }
            );

            if (loopRes.IsCompleted) {
                Console.WriteLine ("Loop was successful");
            }
            if (loopRes.LowestBreakIteration.HasValue) {
                Console.WriteLine ("loopRes.LowestBreakIteration.Value = " + loopRes.LowestBreakIteration.Value);
            }
        } 

从我在网上看到的,我可以找到Parallel.For&的2个属性。 Parallel.Foreach

  1. IsCompleted
  2. LowestBreakIteration
  3. 对我来说,第一个属性工作正常。但是当涉及3/0的情况时,它会给出除以零的误差。所以第二个if循环应该给我LowestBreakIteration的数量,但它抛出一个错误。如果有任何身体遇到同样的问题并解决了,请告诉我!!

    另外请解释这两个属性的主要目的是什么。在什么情况下它会有所帮助。

    希望很快听到一些人的消息。

2 个答案:

答案 0 :(得分:1)

这是因为它抛出一个异常,改变你的循环只是一点点:

public static void Main (string[] args) 
{ 
    int k = 0; 
    int i = 3; 
    var loopRes = Parallel.For (0, 20, (J, loopState) => 
    { 
        try { k = i / J; }
        catch { loopState.Break(); }
        Console.WriteLine ("Result After division " + J + " = " + k); 
    } 
    ); 

    if (loopRes.IsCompleted) { 
        Console.WriteLine ("Loop was successful"); 
    } 
    if (loopRes.LowestBreakIteration.HasValue) { 
        Console.WriteLine ("loopRes.LowestBreakIteration.Value = " + loopRes.LowestBreakIteration.Value); 
    } 
}  

答案 1 :(得分:0)

通过查看ParallelLoopState对象的LowestBreakIteration属性,您可以看到调用Break方法对最大迭代次数的影响,如下所示:

Parallel.For(1, 20, (i, pls) =>
{
    Console.WriteLine(string.Format(
        "i={0} LowestBreakIteration={1}", i, pls.LowestBreakIteration));
    if (i >= 15)
    {
        pls.Break();
    }
});

/* OUTPUT

i=10 LowestBreakIteration=
i=11 LowestBreakIteration=
i=19 LowestBreakIteration=
i=1 LowestBreakIteration=
i=2 LowestBreakIteration=19
i=3 LowestBreakIteration=19
i=6 LowestBreakIteration=19
i=7 LowestBreakIteration=19
i=8 LowestBreakIteration=19
i=9 LowestBreakIteration=19
i=12 LowestBreakIteration=19
i=13 LowestBreakIteration=19
i=14 LowestBreakIteration=19
i=15 LowestBreakIteration=19
i=4 LowestBreakIteration=19
i=5 LowestBreakIteration=15

*/

参考:http://www.blackwasp.co.uk/ParallelLoopBreak_2.aspx