gpt4 book ai didi

c# - CancelAsync 是否有效?

转载 作者:行者123 更新时间:2023-11-30 22:39:27 30 4
gpt4 key购买 nike

我制作了一个小应用程序,其中 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;
}
}

关于c# - CancelAsync 是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5702965/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com