Shutting down a Windows service with threads

I have a Windows service written in .NET 3.5 (C #) using System.Threading.Timer, which spawns multiple threads in each callback. These are just regular threads (there is no thread pool), and I set IsBackground = true for each thread, since I will be running managed code.

When a user stops a service, what happens to all threads? Do they know how to skillfully? I don't have code that controls threads through a call or cancel. Is it correct to assume that IsBackground = true is enough to suggest that threads will be deleted and stopped when the user stops the service? What exactly happens when someone stops a Windows service through the Service Manager GUI? Does it kill the process after it fires the OnStop event?

This would be acceptable to me because I built a separate mechanism that allows the user to know for sure that there are no threads before they stop the service. This is done using the 2 WCF methods open with ServiceHost that run inside the Windows service. There is one way to stop the emergence of new threads and another method to query the number of remaining running threads.

I'm just wondering what happens if they skip these steps and just stop the service ... It seems IsBackground helps to achieve this:

+7
multithreading wcf windows-services
source share
1 answer

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 the process from ending. As soon as all the foreground threads belonging to the process are complete, the common language runtime terminates the process. Any remaining background threads stop and do not end.

Setting the IsBackground thread IsBackground to true will allow your Windows service to stop working immediately after the OnStop() callback completes, and all the foreground threads (if any) are completed. Background threads will be stopped, wherever they are in the state of their execution, so if these threads should legally terminate, you will need to use a different mechanism.

One way to do this is to use front threads, which check the ManualResetEvent object, which signals that threads are disconnecting. In the OnStop() ManualResetEvent , set ManualResetEvent , and then wait for the threads to finish using Join() . If they do not exit within a reasonable time, you can forcefully terminate them from the moment you exit the process.

+6
source share

All Articles