5
如果我要定期檢查是否存在取消請求,我會用下面不斷下面的代碼我的DoWork事件處理中:有沒有一種乾淨的方式來檢查BackgroundWorker中的取消請求,而無需重複輸入相同的代碼?
if(w.CancellationPending == true)
{
e.Cancel = true;
return;
}
是否有檢查在C#中BackgroundWorker
取消請求一個乾淨的方式無需重複輸入相同的代碼?
請參閱下面的下面的代碼:
void worker_DoWork(object sender, DoWorkEventArgs e)
{
...
BackgroundWorker w = sender as BackgroundWorker;
if(w.CancellationPending == true)
{
e.Cancel = true;
return;
}
some_time_consuming_task...
if(w.CancellationPending == true)
{
e.Cancel = true;
return;
}
another_time_consuming_task...
if(w.CancellationPending == true)
{
e.Cancel = true;
return;
}
...
}
也許讓你的工人狀態的機器,那麼你可以做一個',而(w.CancellationPending!){開關( _someSwitch)...} – MickyD 2014-10-29 12:06:43
將方法拆分爲委託。讓我們說'Action []'然後遍歷循環內的'Actions'檢查if'(w.CancellationPending){e.Cancel = true; return;}' – 2014-10-29 12:09:54
對於你將其解壓縮到一個輔助方法中。 – usr 2014-10-29 12:40:16