我做了一個小應用程序,其中Form
是線程化的(使用BackgroundWorker
),並且在我想要退出的時候,我正在調用函數QuitApplication
的Program
類。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
的可能重複[.NET:如何等待一個BackgroundWorker取消(http://stackoverflow.com/questions/123661/net-how-to-wait-for-a -backgroundworker-cancel) – codingbadger 2011-04-18 12:40:30