取消后台任务 [英] Cancelling Background Tasks

查看:143
本文介绍了取消后台任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的C#应用​​程序关闭时,有时会陷入清理例程中.具体来说,后台工作人员没有关闭.基本上,这就是我试图关闭它的方式:

When my C# application closes it sometimes gets caught in the cleanup routine. Specifically, a background worker is not closing. This is basically how I am attempting to close it:

<罢工> 私有无效App_FormClosing(对象发送者,FormClosingEventArgs e) { backgroundWorker1.CancelAsync(); 而(backgroundWorker1.IsBusy);//卡在这里. }

private void App_FormClosing(object sender, FormClosingEventArgs e) { backgroundWorker1.CancelAsync(); while (backgroundWorker1.IsBusy) ; // Gets stuck here. }

我应该以其他方式执行此操作吗?我正在使用Microsoft Visual C#2008 Express Edition.谢谢.

Is there a different way that I should be doing this? I am using Microsoft Visual C# 2008 Express Edition. Thanks.

其他信息:

后台工作程序似乎没有退出.这就是我所拥有的:

The background worker does not appear to be exiting. This is what I have:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
   while (!backgroundWorker1.CancellationPending)
   {
      // Do something.
   }
}

我还修改了清理代码:

private void App_FormClosing(object sender, FormClosingEventArgs e)
{
   while (backgroundWorker1.IsBusy)
   {
      backgroundWorker1.CancelAsync();
      System.Threading.Thread.Sleep(1000);
   }
}

还有什么我应该做的吗?

Is there something else that I should be doing?

推荐答案

Kevin大风正确地说明了您的BackgroundWorker的DoWork处理程序需要轮询CancellationPending并在请求取消的情况下返回.

Kevin Gale is correct in stating that your BackgroundWorker's DoWork handler needs to poll for CancellationPending and return if a cancellation is requested.

也就是说,如果在关闭应用程序时发生这种情况,您也可以安全地忽略它. BackgroundWorker使用ThreadPool线程,根据定义,该线程是后台线程.保持运行状态不会阻止您的应用程序终止,并且在您的应用程序关闭时线程将自动被关闭.

That being said, if this is happening when your application is shutting down, you can just ignore it safely, as well. BackgroundWorker uses a ThreadPool thread, which is, by definition, a background thread. Leaving this running will not prevent your application from terminating, and the thread will automatically be torn down when your application shuts down.

这篇关于取消后台任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆