如何停止工作线程在服务站一个多线程的Windows服务 [英] How to stop worker threads in a multithreaded Windows service on service stop
问题描述
我有一个使用多个工作线程处理任务,掀起了队列的生产者/消费者排队模型Windows服务。这些任务可以很长时间运行,在许多分钟甚至几个小时的秩序,的不涉及循环的。
I have a Windows service that uses the producer/consumer queue model with multiple worker threads processing tasks off a queue. These tasks can be very long running, in the order of many minutes if not hours, and do not involve loops.
我的问题是关于处理服务停止正常结束处理这些工作线程的最佳途径。我读过的另一个<一href="http://stackoverflow.com/questions/353270/how-can-i-detect-a-threadabortexception-in-a-finally-block-net">SO问题的,使用Thread.Abort的()是不好的设计的征兆,但似乎该服务的onStop()方法只给一个有限的时间内完成服务终止前。我可以做足够的清理在追赶的ThreadAbortException(有不一致的状态没有危险),因此调用Thread.Abort的()上的工作线程似乎确定了我。是吗?有什么办法?
My question is about the best way to handle the service stop to gracefully end processing on these worker threads. I have read in another SO question that using thread.Abort() is a sign of bad design, but it seems that the service OnStop() method is only given a limited amount of time to finish before the service is terminated. I can do sufficient clean-up in the catch for ThreadAbortException (there is no danger of inconsistent state) so calling thread.Abort() on the worker threads seems OK to me. Is it? What are the alternatives?
推荐答案
事实上,中止
应尽量避免。这将是最好的给他们一些时间来正常退出 - 也许超时后,也许考虑放弃他们,那么 - 但最终,服务站可以做,一样的被杀死的过程,而不是
Indeed, Abort
should be avoided. It would be best to give them some time to exit gracefully - then perhaps after a timeout, maybe consider aborting them - but ultimately, service stop can do that just the same by killing the process instead.
我会尝试在我的队列的信号,说:齐平,并退出 - 很像关闭
方法<一href="http://stackoverflow.com/questions/530211/creating-a-blocking-queuet-in-net/530228#530228">here,但也有一些类型的信号时完成。
I would try to have a signal in my queues that says "flush and exit" - much like the Close
method here, but with some kind of signal when complete.
如果你再打中止
- 考虑过程致命伤。尽快杀死它。
If you resort to Abort
- consider the process fatally wounded. Kill it ASAP.
这篇关于如何停止工作线程在服务站一个多线程的Windows服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!