Shutting down the VB.NET service
I have a VB.NET Windows service that I wrote and it works fine. In VB.NET, there is an overridden OnStop () method that is called when the service is stopped. However, it looks like it only stops if someone actually stops the service from the services MMC window.
My question is, is there an event or an overridden method that gets called whenever the service stops, regardless of how it stopped (e.g. restarting the computer, exception and stopping the service, etc.)?
a source to share
There is no event to handle all of these events. Most of the events you listed can be viewed on an individual basis.
- OnShutdown can handle unexpected 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 when every event is not triggered. For example, power events do not fire if I go up and pull out the power cord. Your code should consider closing the service without prior notice.
a source to share
You can override OnShutdown to display power off (reboot) events and OnStop to handle MMC shutdown events.
However, there is no method for handling exceptions. If your service crashes, you need to have exception handling to handle this situation.
a source to share
Based on Inbar Gazit Cancellation in System.ServiceProcess was completed at the beginning of 3.5 RTM , before .NET 3.5 the OnStop event was not called during computer shutdown, so to handle this event, your service would have to override the OnShutdown method (you also need to implement the OnStop event), but it had to be changed in .NET 3.5. According to Inbar, ServiceBase.NET 3.5 will call the Stop method during shutdown, but it might be safer to just implement both methods (meaning inconsistencies between frameworks).
For exceptions, this will depend on how your services (or service components) handle them. The service does not stop if an unhandled exception is thrown. Therefore, handling this situation is entirely up to you: perhaps you make sure that all methods have exception handling, perhaps you added a handled exception handler to your code, etc., but you have to decide the appropriate strategy here.
a source to share