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?
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With