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?
make a loop that starts the thread and adds it to a list, when the answer is found you can then iterate through the list stopping the other threads. If you use a thread pool you will be able to use ThreadPoolExecutor. shutdownNow() to stop all remaining threads in the pool.
The Microsoft C/C++ compiler (MSVC) provides support for creating multithread applications. Consider using more than one thread if your application needs to perform expensive operations that would cause the user interface to become unresponsive.
This means that the Web server is multi-threaded. In the main thread, the server listens to a fixed port. When it receives a TCP connection request, it sets up a TCP connection through another port and services the request in a separate thread. To simplify this programming task, we will develop the code in two stages.
Multithreading is a model of program execution that allows for multiple threads to be created within a process, executing independently but concurrently sharing process resources. Depending on the hardware, threads can run fully parallel if they are distributed to their own CPU core.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With