2012-10-11 53 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