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.
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,
Abortshould 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.I would try to have a signal in my queues that says ‘flush and exit’ – much like the
Closemethod here, but with some kind of signal when complete.If you resort to
Abort– consider the process fatally wounded. Kill it ASAP.