Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if I stop my Windows Service while it is processing a WCF request?

I'm guessing that all execution immediately ceases and the calling end gets a timeout. What exactly happens when you stop a service, and how much control do you have over it?

like image 849
Brian MacKay Avatar asked Jul 26 '12 17:07

Brian MacKay


1 Answers

When the Service Control Manager tells your service to stop, .Net ServiceBase sets the status to SERVICE_STOP_PENDING and calls your service's OnStop method. What you do with that notification is up to you. Ideally, you will have some mechanism such as the use of a CancellationToken to notify any of your threads currently working that they need to wrap it up and exit as quickly as possible. In your case it may involve closing your ServiceHost. Your OnStop method should wait until it knows that's been accomplished (by Joining the threads, for example) before returning. There are ways to notify the Service Control Manager that you need more time, or to just let it know that you got the notification and you're actively working on stopping (SERVICE_STATUS dwcheckpoint).

If you just return immediately from your OnStop (or don't bother implementing it), then I think your service's threads will all be forcibly terminated quickly. I don't know for sure, because I've never tried this. I always implement OnStop, and only return after everything's cleaned up. If you implement OnStop, but take a very long time to return without letting the Service Control Manager know that you're working on it, then it will wait a little while (20 seconds for service stop...it's a registry setting), and then terminate your threads.

The right thing to do is write your service so that it starts quickly, stops quickly, pauses and continues quickly, etc. As you can see from the description above, exactly what happens in your case, depends entirely on how your service was implemented. Only you have the information to "know for sure".

http://blogs.msdn.com/b/bclteam/archive/2009/02/19/in-depth-how-net-managed-services-interact-with-the-servicecontrolmanager-scm-kim-hamilton.aspx

like image 164
hatchet - done with SOverflow Avatar answered Nov 17 '22 00:11

hatchet - done with SOverflow