How to stop worker threads in a multithreaded Windows service on service stop

Posted by RobW on Stack Overflow See other posts from Stack Overflow or by RobW
Published on 2009-04-01T10:51:00Z Indexed on 2010/04/27 7:43 UTC
Read the original article Hit count: 472

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?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about windows-services