如何停止工作线程在服务站一个多线程的Windows服务服务站、线程、多线程、工作

2023-09-03 03:33:13 作者:星空下的眼淚

我有一个使用多个工作线程处理任务,掀起了队列的生产者/消费者排队模型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.

我的问题是关于处理服务停止正常结束处理这些工作线程的最佳途径。我读过的另一个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.

我会尝试在我的队列的信号,说:齐平,并退出 - 很像关闭方法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.