CancelAsync是否工作
本文关键字:工作 是否 CancelAsync | 更新日期: 2023-09-27 17:50:23
我做了一个小的应用程序,其中Form
是线程(使用BackgroundWorker
),并在形式我调用QuitApplication
函数在Program
类,当我想退出。
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();
}
我用guiThread.WorkerSupportsCancellation = true
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;
}
}