取消后台任务

编程入门 行业动态 更新时间:2024-10-22 21:28:39
本文介绍了取消后台任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当我的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.

更多推荐

取消后台任务

本文发布于:2023-11-15 05:45:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1591673.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:后台

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!