2016-01-15 72 views
0

如何對C#foreach循環進行時間限制,每次迭代都應該正常運行,並且當前一個循環花費的時間超過30秒時,將進入下一次迭代。如何限制C#foreach循環執行最大時間限制的迭代

使用秒錶,定時器......但這些都是允許運行迭代,每30秒,任何人都可以幫助...

+0

使用'stopwatch'來檢測運行時間,並使用'continue'去下一個迭代 –

回答

0

或者在這裏你已經有一個任務的例子。

foreach(var item in collection) 
{ 
    int timeout = 30000; 
    var task = Task.Run(()=>SomeOperationAsync()); 
    await Task.WhenAny(task, Task.Delay(timeout)); 
} 

當然,如果您的手術在30秒之前完成,並且可能導致某種情況,您也可以使用檢查來增強此檢查。

+0

謝謝曼紐爾的迴應......它工作得很好......當我嘗試之前我錯過了等待任何關鍵字,嘗試使用相同的線程。再次感謝您的幫助!! – user9

+0

我很高興它對你有幫助。別客氣 :) –

0

您將有產卵每次迭代一個單獨的線程。但是,由於匿名代理,您幾乎可以使代碼在本地執行。

foreach(var item in collection) 
{ 
    var threadItem = item; 
    ManualResetEvent mre = new ManualResetEvent(false); 

    Thread workerThread = new Thread(() => 
     { 
     try 
      { 
       // do something with threadItem in here 
      } 
     finally 
      { 
       mre.Set(); 
      } 
     }); 

    workerThread.Start(); 
    mre.WaitOne(30000); // this will wait for up to 30 sec before proceeding to the next iteration. 
    } 
+0

謝謝你的迴應,這個工作,但在下一次迭代之前等待30秒...但我想循環繼續正常無論如何它不應該超過30秒......所以不需要等待每一次迭代......再次感謝 – user9

-1

只需使用一些線索:

public static void ThreadAbortDemo(int sleeptime) 
    { 
     int[] collection = new int[10]; 
     foreach (var item in collection) 
     { 
      System.Threading.Thread thread = new System.Threading.Thread(() => 
      { 
       try 
       { 
        // do your stuff with item 
       } 
       catch (System.Threading.ThreadAbortException) 
       { 
        // this thread is disposed by thread.Abort() statement 
        // do some stuff here before exit this thread 
       } 
      }); 
      thread.Start(); 
      System.Threading.Timer timer = new System.Threading.Timer((o) => 
      { 
       try 
       { 
        thread.Abort(o); 
       } 
       catch 
       { 
        // the thread is done before Abort statement called 
       } 
      },new object(),sleeptime,System.Threading.Timeout.Infinite); 
     } 
    } 

上面只是例子的代碼,你可以像你的任務或線程池的另一種方式,以減少創建線程的成本。