views:

812

answers:

3

I have a VB.NET Windows Service that I wrote and it works fine. In VB.NET there is an overrideable method called OnStop() that gets called when the service is stopped. However, it appears it only gets stopped if someone actually stops the service from the Services MMC Console Window.

My question is, is there an event or an overridable method that gets called whenever the service stops, regardless of how it got stopped (e.g. Computer reboots, Exception occured and shut down service, etc....)?

A: 

You can override OnShutdown to capture power down events (reboots), and OnStop to handle MMC shutdown events.

However, there isn't a method that's called to handle exceptions. If your service crashes, you'll need to have exception handling in place to handle that situation.

Reed Copsey
+4  A: 

There is no one event to handle all of those events. Most of the events you listed can be dealt with on an individual basis.

  • OnShutdown can overriden to deal with non-sudden power events (user shutdown, reboot, etc ...)
  • Application.UnhandledException can be used for unhandled exceptions

Note that you cannot depend on these events firing 100% of the time. There are situations where each event will fail to run. For instance, the power related events won't fire if I walk up and rip out the power cord. Your code must account for the service shutting down without any prior notification.

JaredPar
A: 

Based on Inbar Gazit's Change in System.ServiceProcess shutdown is coming in 3.5 RTM post, prior to .NET 3.5, the OnStop event did not get called during computer shutdown, so to handle this event, your service would need to override the OnShutdown method (you would also need to implement the OnStop event), but it was supposed to be changed in .NET 3.5. According to Inbar, the .NET 3.5 version of ServiceBase would call the Stop method during shutdown, but it may be safer just to implement both methods (keeping in mind the discrepancies between the frameworks).

With respect to exceptions, it will depend on how your service (or service components) handles them. The service does not get stopped if an unhandled exception occurs, it crashes. So handling this situation is totally up to you: maybe you make sure that all methods have exception handling, maybe you add an unhandled exception handler to your code, etc, but you have to decide the appropriate strategy here.

Alek Davis