2009-08-27 69 views

回答

3

看看這個教程:http://www.albahari.com/threading/part3.aspx

爲了使System.ComponentModel.BackgroundWorker線程支持取消,需要啓動線程之前設置WorkerSupportsCancellation屬性爲True。

然後,您可以調用BackgroundWorker的.CancelAsync方法來取消該線程。

+0

我已閱讀上面的文章,但我需要1分鐘後 – 2009-08-27 14:40:19

+2

終止我的背景工人約在調用線程創建一個System.Threading.Timer對象並設定它1分鐘什麼。當timer事件觸發時,調用BackgroundWorker線程的.CancelAsync方法。 – TLiebe 2009-08-27 14:42:16

0

BackgroundWorker不支持這兩種情況。 以下是支持這些情況的一些代碼的開始。

class MyBackgroundWorker :BackgroundWorker { 
    public MyBackgroundWorker() { 
     WorkerReportsProgress = true; 
     WorkerSupportsCancellation = true; 
    } 

    protected override void OnDoWork(DoWorkEventArgs e) { 
     var thread = Thread.CurrentThread; 
     using(var cancelTimeout = new System.Threading.Timer(o => CancelAsync(), null, TimeSpan.FromMinutes(1), TimeSpan.Zero)) 
     using(var abortTimeout = new System.Threading.Timer(o => thread.Abort(), null, TimeSpan.FromMinutes(2), TimeSpan.Zero)) { 
      for(int i = 0; i <= 100; i += 20) { 
       ReportProgress(i); 

       if(CancellationPending) { 
        e.Cancel = true; 
        return; 
       } 

       Thread.Sleep(1000); //do work 
      } 
      e.Result = "My Result"; //report result 

      base.OnDoWork(e); 
     } 
    } 
} 
+0

'Task.Delay'是'Thread.Sleep'的2017版本。 – mayu 2017-07-28 06:27:55