Preferred way of ending a windows service.

F

Frank Rizzo

I have a windows service which spawns a lot of threads that are all busy
doing various things. What is the preferred way of telling all these
threads to stop? For a situation, when the user stops the service or
the system is shutting down.

I could kill the threads, but that generates ThreadAbortException all
over the place and isn't elegant.

Regards
 
L

Larry Smith

Frank Rizzo said:
I have a windows service which spawns a lot of threads that are all busy
doing various things. What is the preferred way of telling all these
threads to stop? For a situation, when the user stops the service or the
system is shutting down.

I could kill the threads, but that generates ThreadAbortException all over
the place and isn't elegant.

It's your responsibility to control your own threads and there are a variety
of ways to do this. An event semaphore like "EventWaitHandle" is one way.
The main thread can signal this and all threads should respect it by
immediately exiting once detected (they have to check for it perioidically
of course so your threads should be designed to perform their work in
discrete, interruptible units). The main thread can then exit as soon as it
determines that all it's threads have exited.
 
N

Nicholas Paldino [.NET/C# MVP]

Frank,

Is there work that you have to have completed in the thread in the event
of a shutdown? If so, then you will have to place checks in your threaded
code to check at certain points if a shutdown is occuring. If it is, then
you can elegantly exit the thread. Of course, this means that you have to
set this flag on shutdown, and wait for the threads to complete.

If you don't have any need for work to complete in the threads in the
event of a shutdown, then killing the threads is just fine (and I would
trade the perceived lack of elegance of such a method for the time it would
take to implement what I mentioned above).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top