后台工作线程在程序关闭时未关闭?

发布于 2024-08-20 13:00:03 字数 219 浏览 3 评论 0原文

我有一个简单的程序,有后台工作人员,它不停地运行,无论我什么时候关闭它,它总会有一些仍在运行(或全部),而且我注意到关闭应用程序并没有完全关闭杀掉它。运行几次后,Windows 任务管理器的进程选项卡上仍保留有进程(每次运行 1 个)。

他们为什么留下来?我该怎么做才能让他们不这样做?

PS:我读过有关后台工作人员在应用程序关闭时的行为的问题,但我想它当时并没有按预期行事。有什么建议吗?

I have a simple program that has backgroundworkers, and it runs with no stop, and no matter when I close it, it will always have some still running (or all of them) and I've noticed that closing the application doesn't completly kill it. After running it some times, there are processes (1 for each run) that remain on the process tab of the windows task manager.

Why do they remain? what do I do for them not to ?

ps.: I've read questions about backgroundworker's behavour in application closing, but I guess it's not acting as intended then. Any suggestions ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

深爱不及久伴 2024-08-27 13:00:03

更好的方法是在应用程序关闭之前使用事件或自定义操作来停止/终止线程。

如下

private void ButtonStopBGWorker_Click(object sender, RoutedEventArgs e)
{
 BackgroundWorker worker = sender as BackgroundWorker;
 if ((worker.CancellationPending == true))
   {
      e.Cancel = true;
      break;
   }
}

论坛上的这篇文章会给你更多见解。
另外,请查看 MSDN,了解有关如何管理 后台工作者线程

希望有帮助

A better approach is to stop / kill the thread using an event or custom action before applicaion in closed.

like as follows

private void ButtonStopBGWorker_Click(object sender, RoutedEventArgs e)
{
 BackgroundWorker worker = sender as BackgroundWorker;
 if ((worker.CancellationPending == true))
   {
      e.Cancel = true;
      break;
   }
}

This post at the forum will give you more insight.
Also, have a look at MSDN for details about how to manage Backgroundworker Threads

Hope it helps

从来不烧饼 2024-08-27 13:00:03

它们是您自己旋转的线程吗?如果您创建自己的线程,我相信您需要将它们设置为后台线程,以便让它们与主线程一起终止。否则他们将保持该进程的运行。从内存中将给定线程设置为后台的代码类似于:

Thread t = new Thread(YouStartMethod);
t.IsBackground = true;
t.Start();

希望这有帮助

Are they threads you spin up yourself? If you create your own threads I believe you need to set them to background threads in order to have them terminate along with the main thread. Otherwise they will keep the process alive. From memory the code to set a given thread to background is something like:

Thread t = new Thread(YouStartMethod);
t.IsBackground = true;
t.Start();

Hope this helps

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文