Windows Service OnStop when computer shutdown

c#, windows-services

Solution

Yes. `OnStop()` gets called when the machine is shutdown. `OnShutdown()` is for when you need to know specifically that the machine is being shutdown.

UPDATE: As has been pointed out in the comments since this was first posted, this is no longer necessarily the case. So your code should be written with the assumption that `OnStop()` may or may not be called when the machine is shut down. If you need to clean up during a shutdown, handle `OnShutdown()`.

Problem

I'm writing a Windows Service in C#. I want to take the same action for when the service is stopped by the Service control panel as when the system is shutdown. I want to take the same action for either case. Do I have to override `ServiceBase.OnShutdown()`, or is overriding `ServiceBase.OnStop()` for both cases sufficient?

Original source