2017-09-05 231 views
0

我目前正在运行一个Parallel.ForEach循环,其中包含一个while循环。C# - Parallel.ForEach循环在嵌套while循环停止后不会停止

那些将被运行直到一个条件取消他们。正如你将看到的while循环只有在有效的响应将userChanged布尔值设置为true时才会运行。

我的问题:loopState.Break();代码似乎

不停止Parallel.ForEach循环。我究竟做错了什么?该userChanged布尔设置为true

后,功能将跳回以下行:

Parallel.ForEach(dataGridView1.Rows.Cast<DataGridViewRow>(), (row, loopState) => 

,并重新启动代码。我赞赏任何形式的建议和帮助!

示例代码:

private void function() 
{ 
    Parallel.ForEach(dataGridView1.Rows.Cast<DataGridViewRow>(), (row, loopState) => 
    { 
     try 
     { 
      // HttpWebRequest 

      bool userChanged = false; 

      while (!userChanged) 
      { 
       try 
       { 
        WebClient client1 = new WebClient 
        { 
         Proxy = null 
        }; 

        client1.Headers["Accept-Language"] = "en-us"; 

        if (client1.DownloadString("https://url.com/" + row.Cells[0].Value.ToString()).Contains("Sorry, that page doesn’t exist!")) 
        { 
         if (!userChanged) 
         { 
          // Request 

          if (/* condition is true */) 
          { 
           MessageBox.Show("Success", "Info", MessageBoxButtons.OK); 
           userChanged = true; 

           requestStream.Close(); 

           loopState.Break(); 
          } 
         } 
        } 
        else 
        { 
         // Call another function 
        } 
       } 
       catch (WebException ex) 
       { 
        MessageBox.Show(ex.Message); 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 

    }); 
} 
+0

[loopstate.Break(),loopState.Stop()和CancellationTokenSource.Cancel()]之间有什么区别可能的副本(https://stackoverflow.com/questions/8818203/what-is-difference-between- loopstate-break-loopstate-stop-and-cancellationt) – Reniuz

+1

我没有看到任何CPU密集型的事情发生在这里。似乎并不适合Parallel.ForEach。你有没有考虑过使用异步/等待Task.WhenAll?你所做的只是进行网络通话 –

回答

2

尝试使用loopState.Stop()

根据文档:

调用歇方法通知操作,当前的一个迭代后不必须执行。但是,如果它们还没有执行,那么在当前执行之前的所有迭代都必须执行。并且不能保证当前迭代之后的迭代肯定不会执行。

MSDN

1

是的,取消必须是合作。

while (!userChanged && !loopState.ShouldExitCurrentIteration) 

我认为你甚至可以不用userChanged这是只有当地的国家。 ShouldExitCurrentIteration在此迭代与其他所有人之间共享。