2017-04-04 22 views
3

谷歌並沒有幫助我,所以也沒有。打破平行ForEach從外部

var timer = new System.Timers.Timer(5000); 
timer.Elapsed += BreakEvent; 
timer.Enabled = true; 

Parallel.ForEach<string>(fileNames, (fileName, state) => 
{ 
    try 
    { 
     ProcessFile(fileName); 
    } 
    catch (Exception) 
    { 

    } 
    finally 
    { 

    } 
}); 

我想在5秒後,以打破這種ForEach環路(在BreakEvent)。

當然,它可能是一個按鈕或任何東西。

我知道(在我的例子),打破

state.Stop(); 

但它仍然在循環中。

這有可能嗎?

編輯:

大家誰尋找其他的方式,我只是雖然這件事:

var timer = new System.Timers.Timer(5000); 

timer.Elapsed += new System.Timers.ElapsedEventHandler((obj, args) => 
{ 
    state.Stop(); 
}); 

timer.Enabled = true; 
+0

[相關問題](http://stackoverflow.com/questions/12571048/break-parallel-foreach) – stuartd

+0

@MassimilianoKraus這是我最初的想法是,但這個問題涉及從循環內部打破,而不是從外部打破。 – stuartd

+0

是的,這完全是關於從裏面打破。 – Yelhigh

回答

5

我建議使用取消

// Cancel after 5 seconds (5000 ms) 
using (var cts = new CancellationTokenSource(5000)) 
{ 
    var po = new ParallelOptions() 
    { 
     CancellationToken = cts.Token, 
    }; 

    try 
    { 
     Parallel.ForEach(fileNames, po, (fileName) => 
     { 
      //TODO: put relevant code here 
     }); 
    } 
    catch (OperationCanceledException e) 
    { 
     //TODO: Cancelled 
    } 
} 
+0

O,這是個好主意! :)我沒想過,謝謝你! – Yelhigh