2014-10-29 16 views
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; 
    } 

    ... 
} 
+4

也許讓你的工人狀態的機器,那麼你可以做一個',而(w.CancellationPending!){開關( _someSwitch)...} – MickyD 2014-10-29 12:06:43

+6

將方法拆分爲委託。讓我們說'Action []'然後遍歷循環內的'Actions'檢查if'(w.CancellationPending){e.Cancel = true; return;}' – 2014-10-29 12:09:54

+3

對於你將其解壓縮到一個輔助方法中。 – usr 2014-10-29 12:40:16

回答

5

使用while循環和代表

添加您的任務委託列表然後測試條件的循環。

您可以使用自定義的行動委託簡化這項任務(見:http://msdn.microsoft.com/en-us/library/system.action(v=vs.110).aspx

void worker_DoWork(object sender, DoWorkEventArgs e) 
{ 
    List<Action> delegates = new List<Action>(); 
    delegates.add(some_time_consuming_task); 
    delegates.add(another_time_consuming_task); 

    BackgroundWorker w = sender as BackgroundWorker;  
    while(!w.CancellationPending && delegate.Count!=0) 
    { 
     delegates[0](); 
     delegates.remove(0); 
    } 

    if(w.CancellationPending) 
     e.Cancel = true; 
} 
相關問題