CancelAsync 是否有效?
我制作了一个小型应用程序,其中 Form
是线程化的(使用 BackgroundWorker
),并在表单中调用 QuitApplication
中的函数 QuitApplication
当我想退出时,使用 code>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
I've made a small app where Form
is threaded (using BackgroundWorker
), and in the form I'm calling a function QuitApplication
in Program
class when I want to quit.
The DoWork
looks like this:
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);
}
}
and in the Form1 class i have this method attached to the closing of the window:
void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
Program.instance.SetStatus("Closing down...", 0);
Program.QuitApplication();
}
So what i want is to ensure that everything quits when I press the X on the window. However, the if( worker.CancellationPending == true )
never hits... why is this?
QuitApplication looks like this:
public static void QuitApplication()
{
Program.instance.guiThread.CancelAsync();
Application.Exit();
}
And Im using guiThread.WorkerSupportsCancellation = true
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
CancelAsync
正在设置CancellationPending
属性,但随后您立即退出应用程序,而没有让后台线程有机会检测到并关闭。您需要更改 UI 代码以等待后台线程完成。就我个人而言,当我编写这样的应用程序时,我使表单关闭按钮充当取消按钮,而不是立即退出。对于最终用户来说更安全。例如:
CancelAsync
is setting theCancellationPending
property, but then you immediately quit the application without giving the background thread a chance to detect that and shut down. You need to change your UI code to wait for the background thread to finish.Personally, when I write apps like this, I make the form close button act like a Cancel button rather than quit immediately. It's a lot safer for the end user. For example: