2012-12-17 78 views
2

這是dowork代碼。我甚至已經完成了這一步。在e.cancel = true之後,DoWork再次運行,它進入while循環,它將e.Cancel再次設置爲true,然後退出該函數並從不運行Completed函數。後臺工作人員在e.cancel = true之後不會運行「RunWorkerCompleted」;

private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) 
    { 
     BackgroundWorker worker = sender as BackgroundWorker; 
     //While the song is not over 
      while (!worker.CancellationPending) 
      { 

       if (progressBar1.Value == progressBar1.Maximum) 
       { 

        e.Cancel = true; 
        return; 
       } 
       else 
       { 
        //Keep ticking the progress bar one second 
        worker.ReportProgress(0); 
        Thread.Sleep(1000); 
       } 
      } 
      e.Cancel = true; 
      return; 



    } 

這是取消工作人員的代碼。 WaitOne()將阻塞,直到它從RunWorkerCompleted獲得一個信號。

if (this.backgroundWorker2.IsBusy) 
     { 
      this.backgroundWorker2.CancelAsync(); 

      _resetEvent.WaitOne(); 

     } 

編輯:請注意,我已經做到了這一點VV

backgroundWorker2.RunWorkerCompleted += backgroundWorker2_RunWorkerCompleted; 
backgroundWorker2.WorkerSupportsCancellation = true; 
+0

修復對不起,這個網站總是困惑我,我從來沒有意識到我沒有給出最好的答案。 – Man

回答

1

沒有設置

BackgroundWorker.WorkerSupportsCancellation = true 

+0

是的,我正在編輯這個問題。 – Man