xr280xr
xr280xr

Reputation: 13302

What happens if Windows service doesn't exit a thread when stopping?

I have a .NET Windows service that runs multiple threads. A developer added some new threads to it but forgot to add code to exit the threads before the service stops. When I stop the service, it appears to stop normally, but the exe process continues running for several seconds after the service has stopped. What is happening during this time and what happens to the threads?

Upvotes: 3

Views: 1619

Answers (2)

Matt Davis
Matt Davis

Reputation: 46044

I assume the delay is there because services tend to do things that are considered "more substantial" than simply servicing button clicks and keystrokes from the user, e.g., closing database connections, disconnecting network connections, stopping drivers, etc. These things may take a few seconds, so the OS grants some amount of time for a clean shutdown. However, eventually, the OS will terminate the process, which will kill any threads that are still running.

Threads in .NET can be classified as foreground or background threads. If the threads you are asking about can be terminated abruptly without any undo "harm" to what your service is doing, mark them as background threads so that they do not hold up termination of the process.

Upvotes: 2

Martin James
Martin James

Reputation: 24857

If you don't terminate the threads, but handle the ServiceStop message correctly, the other threads continue to run for ~20 secs, then the OS kills off the service process, killing the threads along the way.

Doesn't seem to do any harm, in general.

Upvotes: 2

Related Questions