2012-08-05 43 views

回答

1

我的建議是去閱讀MSDN上這裏的示例代碼:BackgroundWorker Class (MSDN)。他們的例子顯示了取消工人的方式。


您還可以使用break退出循環:

bool stop = false; 

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
{ 
    while(true) 
    { 
     if(stop) 
      break; // this will exit the while loop 

     cpuView(); 
     gpuView(); 
     Thread.Sleep(1000); 
    } 
} 
+0

SpinWait好得多 – GSerjo 2012-08-05 17:01:22

+0

的方法和現在你有2個問題,P – leppie 2012-08-05 17:01:46

0

創建具有消除一個布爾和暫停狀態的自定義類。 在您的backgroundWorker.DoWork([MyCustomObject的實例])中傳遞該類中的對象參數

您可以使用按鈕事件從原始線程更新屬性。

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
{ 
    MyCustomObject cancellationStatus = e.Argument as MyCustomObject 
    while(!cancellationStatus.Cancelled) 
    { 
     if(!cancellationStatus.Paused) 
     { 
      cpuView(); 
      gpuView(); 
     } 
     Thread.Sleep(1000); 
    } 
} 
+0

在NED我使用BackgroundWorker的取消未完成的選項。謝謝。 – user1544479 2012-08-05 17:19:43

0

首先你做一個方法來完成任務。然後聲明Threading類的實例作爲

Threading thrd=new Threading(signature of method defined) 

然後寫在任何你想要的按鈕的事件處理程序。

t.start() 
t.abort() 
t.resume() 

的啓動,停止或恢復線程