我怎样才能做到ThreadPool.Join? [英] How can I accomplish ThreadPool.Join?

查看:256
本文介绍了我怎样才能做到ThreadPool.Join?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个使用Windows服务 ThreadPool.QueueUserWorkItem()。每个线程都是一个短暂的任务。

I am writing a windows service that uses ThreadPool.QueueUserWorkItem(). Each thread is a short-lived task.

在该服务被停止,我需要确保所有线程当前正在执行的完整。有没有等待,直到队列清除​​自身的一些方式?

When the service is stopped, I need to make sure that all the threads that are currently executing complete. Is there some way of waiting until the queue clears itself?

推荐答案

您可以创建在每个线程的事件(如的ManualResetEvent ),并将其保存在同步列表(使用锁定构造)。将事件或当任务完成列表中删除。

You could create an event (e.g. ManualResetEvent) in each thread, and keep it in a synchronised list (using the lock construct). Set the event or remove it from the list when the task is finished.

当你想加入,你可以使用 WaitHandle.WaitAll的 MSDN文档)等待所有的事件发出信号。

When you want to join, you can use WaitHandle.WaitAll (MSDN documentation) to wait for all the events to be signalled.

这是一个黑客,但我不能看到如何将其降低到什么简单!

It's a hack, but I can't see how to reduce it to anything simpler!

编辑:此外,你可以确保没有新​​的事件被发布,然后等待几秒钟。如果他们确实是短暂的,你不会有任何问题。更简单,但更哈克

additionally, you could ensure that no new events get posted, then wait a couple of seconds. If they are indeed short-lived, you'll have no problem. Even simpler, but more hacky.

最后,如果它只是一个时间短量,该服务将不会退出,直到所有线程都死了(除非他们是后台线程);因此,如果这是很短的时间量,服务控制管理器不会介意一秒钟左右 - 你可以把它们到期 - 。以我的经验

Finally, if it's just a short amount of time, the service won't exit until all threads have died (unless they are background threads); so if it's a short amount of time, the service control manager won't mind a second or so - you can just leave them to expire - in my experience.

这篇关于我怎样才能做到ThreadPool.Join?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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