Handle STOP in a multi-threaded Windows service

S

Simon Niederberger

Hi

I've written a Windows Service which has
- several (0-100) listeners threads which spawn worker threads based on
events, timers etc
- several (0-300) worker threads which handle data (message based) and
terminate after processing

I'm wondering what exactly happens when I stop the service. I don't see an
ThreadAbortedException, but I'm worried my worker threads might be
terminated in the middle of processing. My Server.OnStop is empty.

Does Windows wait for all threads to terminate in a given timespan, then
send an Abort to all running threads? Or does it send Abort directly?

Any help, including pointing to good URL (haven't found any so far) or
better newsgroup is very much appreciated.

Simon
 
W

Willy Denoyette [MVP]

Inline

Willy.

Simon Niederberger said:
Hi

I've written a Windows Service which has
- several (0-100) listeners threads which spawn worker threads based on
events, timers etc
- several (0-300) worker threads which handle data (message based) and
terminate after processing

Such high number of threads is just a waste of CPU and memory resources, you
can do with far less than that.

I'm wondering what exactly happens when I stop the service. I don't see an
ThreadAbortedException, but I'm worried my worker threads might be
terminated in the middle of processing. My Server.OnStop is empty.

Does Windows wait for all threads to terminate in a given timespan, then
send an Abort to all running threads? Or does it send Abort directly?
The OS doesn't send anything at all, the CLR stops the threads cold by
issuing a Thread.Abort as part of the CLR's orderly shutdown procedure. If
this is not what you want, you should handle your thread shutdown yourself
in OnStop. One way of doing this is to have your threads inspect a shared
flag that you could set in OnClose, once the flag set, the active thread
should stop it's activity and return, the OnStop procedure can use
Thread.Join(timeout) on each thread you have started.
Note that all this should be done within 30 seconds, as otherwise the SCM
will consider that the service failed to shutdown.
 
S

Simon Niederberger

Thanks a lot, perfect answer (within hours!) I'll look into reducing the
number of threads, but I feel that won't be to easy.

Cheers
Simon
 

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