2011-04-18 53 views
2

我做了一個小應用程序,其中Form是線程化的(使用BackgroundWorker),並且在我想要退出的時候,我正在調用函數QuitApplicationProgram類。CancelAsync是否工作?

DoWork看起來是這樣的:

static void guiThread_DoWork(object sender, DoWorkEventArgs e) 
{ 
    BackgroundWorker worker = sender as BackgroundWorker; 

    while (true) 
    { 
     if (worker.CancellationPending == true) 
     { 
      e.Cancel = true; 
      break; 
     } 

     if (Program.instance.form != null) 
     { 
      Program.instance.form.UpdateStatus(Program.instance.statusText, Program.instance.statusProgress); 
     } 

     Thread.Sleep(GUI_THREAD_UPDATE_TIME); 
    } 
} 

,並在Form1類我已經貼在車窗的關閉這個方法:

void Form1_FormClosed(object sender, FormClosedEventArgs e) 
{ 
    Program.instance.SetStatus("Closing down...", 0); 

    Program.QuitApplication(); 
} 

所以我想的是,以確保一切當我按下窗口上的X時退出。然而,if(worker.CancellationPending == true)從來沒有打...爲什麼這樣?

QuitApplication看起來是這樣的:

public static void QuitApplication() 
{ 
    Program.instance.guiThread.CancelAsync(); 

    Application.Exit(); 
} 

而且使用im guiThread.WorkerSupportsCancellation = true

+0

的可能重複[.NET:如何等待一個BackgroundWorker取消(http://stackoverflow.com/questions/123661/net-how-to-wait-for-a -backgroundworker-cancel) – codingbadger 2011-04-18 12:40:30

回答

3

CancelAsync是設置CancellationPending屬性,但然後立即退出應用程序,而不讓後臺線程有機會來檢測和關閉下。您需要更改UI代碼以等待後臺線程完成。個人而言,當我編寫這樣的應用程序時,我使表單關閉按鈕的作用類似於取消按鈕,而不是立即退出。對於最終用戶來說這更安全。例如:

private void abortButton_Click(object sender, EventArgs e) { 
    // I would normally prompt the user here for safety. 
    worker.CancelAsync(); 
} 

private void Form1_FormClosing(object sender, FormClosingEventArgs e) { 
    if(worker.IsBusy) { 
     // If we are still processing, it's not very friendly to suddenly abort without warning. 
     // Convert it into a polite request instead. 
     abortButton.PerformClick(); 
     e.Cancel = true; 
    } 
} 
+0

我可以在QuitApplication中做一段時間(guiThread.isBusy); Application.Exit之前?但是,dows Application.Exit終止ALL? – Jason94 2011-04-18 12:45:36

+0

傑森,看看巴里的問題鏈接爲答案。我所說的是,我認爲用我的建議來完全避免這個問題會更方便用戶。 – 2011-04-18 12:49:35

+0

你如何讓Form1瞭解工人?或者你的意思是:if(Program.instance.worker.IsBusy)? – Jason94 2011-04-18 13:13:56