I have a windows service written in .NET 3.5 (c#) with a System.Threading.Timer that spawns several Threads in each callback. These are just normal threads (no Thread Pool) and I've set the IsBackground = true on each thread since I'm only going to be running managed code.
When a user stops the service, what happens to all the threads? Do they die gracefully? I don't have any code that manages the threads via calling join or abort. Is it correct to assume the IsBackground = true is enough to assume the threads will be disposed and stopped when a user stops the service? What exactly happens when someone stops a windows service via the Service Manager GUI? Does it kill the process after it fires the OnStop event?
This would actually be acceptable for me because I've built a separate mechanism that allows a user know for sure there are no threads before they stop the service. This is done via 2 WCF methods exposed from a ServiceHost that runs inside the Windows Service. There's one method to stop spawning new threads and another method to query how many running threads there are left.
I'm just curious what happens if they skip those steps and just stop the service... It seems the IsBackground helps achieve this:
From the MSDN link you provided:
A thread is either a background thread or a foreground thread. Background threads are identical to foreground threads, except that background threads do not prevent a process from terminating. Once all foreground threads belonging to a process have terminated, the common language runtime ends the process. Any remaining background threads are stopped and do not complete.
Setting a thread's IsBackground
property to true
will allow your Windows service to terminate immediately once the OnStop()
callback is finished executing and all foreground threads (if any) have exited. The background threads will be stopped wherever they happen to be in their execution state, so if these threads need to terminate gracefully, you'll need to use a different mechanism.
One way to do this would be to use foreground threads that check a ManualResetEvent
object that signals the threads to shutdown. In your OnStop()
callback, set the ManualResetEvent
and then wait for the threads to exit using Join()
. If they don't exit in a reasonable time, you can forcefully terminate them since the process is exiting.
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