How to fail ServiceBase.OnStop()

Writing a service in .NET entails inheriting from the System.ServicProcess.ServiceBase class, which is a lot better than writing the necessary Win32 API calls. However, while ServiceBase allows you to react to a stop request on your service by overriding OnStop (an example of the Template Method pattern) there is no obvious way to respond to that call and say ‘I cannot stop now, please try later’. This becomes important if your service is in the middle of a business transaction that you either need to finish or abort in order to avoid leaving your state invalid. There are no parameters to set a ‘CannotStopNow’ variable on, or any return value. There are some properties that look useful at first glance, like CanStop, but they are actually about what options are presented to the system.

The best answer I can come up with is courtesy of Lutz Roeder’s Reflector. Looking at the call to OnStop from DeferredStop it looks as though throwing an exception from OnStop is caught by DeferredStop which then reports that the Stop Failed.

I’ll let you know how it works out, in the meantime if anyone knows of something I have missed here…

 

Advertisements
This entry was posted in Computers and Internet. Bookmark the permalink.

57 Responses to How to fail ServiceBase.OnStop()

  1. Ajit says:

    Did you make any progress on this? I am dealing with the same issue.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s