2012-03-21 73 views
1

幾乎所有背景工作者的例子都是由for循環組成的。但我的要求不需要任何循環。我有以下代碼運行我backgroundworker。如何取消工作進程不使用for循環如何阻止背景工作者

void form_DoWork(LoadingProgress sender, DoWorkEventArgs e) 
    { 

      //for (int i = 0; i < 100; i++) 
     //{ 


     // System.Threading.Thread.Sleep(50); 
     // sender.SetProgress(i, "Step " + i.ToString() + "/100..."); 
     // if (sender.CancellationPending) 
     // { 
     //  e.Cancel = true; 
     //  return; 
     // } 
     //} 
       // heavy database process  
      SomeClass.BulkInsert(ExportLine); 
     } 


    private void ButtonCancelClick(object sender, EventArgs e) 
    { 
     //notify the background worker we want to cancel 
     worker.CancelAsync(); 
     //disable the cancel button and change the status text 
     buttonCancel.Enabled = false; 
     labelStatus.Text = CancellingText; 
    } 
+4

你不能,至少不容易。由於BulkInsert沒有提供取消操作的方法,因此您可以儘量避免中止該線程,而這非常麻煩。 – 2012-03-21 04:53:52

+0

任何替代方案,以顯示耗時處理的進度工作 – arjun 2012-03-21 05:01:04

+0

男士們請任何幫助 – arjun 2012-03-21 05:47:20

回答

2

我不會用BackgroundWorker的,如果這就是你需要做什麼。由於您的班級沒有提供任何提供進度更新的方法,因此它唯一給予您的是編組RunWorkerCompleted方法。

創建Thread類,保留對其的引用並在需要時中止。只要確保當你的後臺工作完成時,如果你用結果更新任何控件,就調用Invoke。

編輯:

下面是它如何工作的原始示例。 (注意:這可能不會編譯,我沒有寫在IDE中)。

Thread _dbThread; 

void DoLongRunningQueryAsync() 
    { 
     bool dbWorkFinished = false; 
     _dbThread = new Thread(() => 
     { 
      // heavy database process  
      SomeClass.BulkInsert(ExportLine); 
      dbWorkFinished = true; 
     }); 
     Thread monitorThread = new Thread(() => 
     { 
      Thread.Sleep(5000); 
      if (!dbWorkFinished) 
      { 
       //Db work took too long. Abort 
       _dbThread.Abort(); 
       this.Invoke(() => MessageBox.Show("Db work took too long. Query aborted");); 
      } 
     }); 
     _dbThread.Start(); 
     monitorThread.Start(); 
    } 


    private void ButtonCancelClick(object sender, EventArgs e) 
    { 
     _dbThread.Abort() 
    } 
+0

請問您可以參考上面的代碼告訴我怎麼做。我需要取消按鈕以取消中止過程。 – arjun 2012-03-22 06:21:09