I have a Windows service class deriving from ServiceBase that uses a System.Timers.Timer to run code at frequent intervals. The handlers for OnStop and OnPause use some signalling with the timer thread to check if the timer is still running and waits for it to finish.

Is there a recommended way of handling delay errors in this situation, such as if the handler is waiting for an unacceptably long time for the timer thread to stop?

Should I just continue waiting until the SCM gives up (but that will put the service into a state where you can't do anything with the service except kill the process, and sometimes a reboot is the only way to restart it)? Or I could throw an exception perhaps (would this leave it in a similar state, or just abort the stop/pause request)?

I'd prefer it if I can reject the request to pause/stop and have the SCM leave it in a state where the user can try to pause/stop again. I could abort the timer thread but sometimes it's locked on other resources that I'd rather it would wait until completion, and just have an error logged with the administrator able to attempt a stop later.

No correct solution


You can use the RequestAdditionalTime method to inform the SCM that you need more time to stop/pause your service.

I butted my head against the SCM giving up causing my service to freeze up like it was sunbathing in Antarctica in June.

The issue for me was that the service did some processing that potentially could take longer than the SCM is willing to wait for it to respond to a stop request.

I like my software to start/exit/pause and even die gracefully.

The solution I implemented was to use a config file. I put an ExecutionMode parameter in the file. At the start of every processing loop, it checks the config file - if ExecutionMode is Pause or Stop, then it executes code to change state and uses SMTP to send an email to the email ids listed in a ServiceChangeNotification paramete. Details included in the email are Machine name, Timestamp, Service Name, Old State, Old State Start Time, Current State, Current State Start Time, Log details.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top