2012-10-11 43 views
3
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); 
      } 
     } 

由于我在互联网上阅读我能找到2个属性的Parallel.For & Parallel.Foreach的Parallel.For属性

  1. IsCompleted
  2. LowestBreakIteration

对我来说第一物业工作正常。但是当涉及到3/0的情况时,它会给出除以零的错误。所以第二个循环应该给我LowestBreakIteration的数量,但是它会抛出一个错误。请让我知道是否有任何组织遇到同一问题并解决它!!

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

希望能尽快听到。

+1

http://books.google.co.il/books?id=EvXX03I5iLYC&pg=PA936&lpg=PA936&dq=%22The+Para llel.For +和+ Parallel.ForEach +方法+返回%22&源= BL&OTS = jFfm4zvSAZ&SIG = tUY6Ht6mHYVa71BMDMNncIU-KJG&HL = EN&SA = X&EI = mLF2UOT4IKOx0AXIiIGADQ&redir_esc = Y#V = onepage&Q =%二条%20Parallel.For%20于是%20Parallel.ForEach%20methods %20return%22&f = false –

+0

请阅读我最近的问题之一.http://stackoverflow.com/questions/12784530/parallel-for-and-break-misunderstanding –

回答

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); 
    } 
} 
+0

调用break会导致其他项目不被调度(在块模式/范围模式),我不认为OP会喜欢。在范围内 - 它会继续大块填充 - 或在大块窗口大小> 1 –

+0

@RoyiNamir,我想我要在这里学习一些东西,我不遵循。你有链接解释,进一步? –

+0

ofcourse。请阅读我最新的问题之一http://stackoverflow.com/questions/12784530/parallel-for-and-break-misunderstanding –

0

你可以看到最大的迭代次数是通过调用该破解方法受到观看ParallelLoopState对象的LowestBreakIteration财产,如下图所示:

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