When a .Net service crashes, does the ServiceBase.OnStop method get called? Will the service be marked as stopped regardless of whether or not the OnStop method is called?
use try-catch and call OnStop yourself; don't rely on 'auto-stop', even if it was 'guaranteed' it is still not a good idea. Services should be as robust as possible.
If by crashes you mean that there is an unhandled exception in your service then the answer is no OnStop will not be called. In general the service will be marked as stopped. But Steven is correct, every 'root' method must have a try-catch block surrounding any code that could throw an exception, your service should never have an unhandled exception.
OnStop() is only called when the service is actually told to stop. This does not include e.g. sytem powerdown, as there is a separate method to override for that (called OnShutdown()
).
Whatever you place in OnStop()
should likely be but into a single separate method, that can be called from both OnStop()
and OnShutdown()
As for catching the odd unexpected exception, I would suggest wrapping the ServiceBase.Run()
call in a try/catch with logging in the catch claus. That should pretty much guarantee you some kind of logging in the event of exceptions.