Stealth Rabbi
Stealth Rabbi

Reputation: 10346

Windows Service OnStop when computer shutdown

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?

Upvotes: 9

Views: 5134

Answers (2)

Pete
Pete

Reputation: 6743

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().

Upvotes: 8

rschoenbach
rschoenbach

Reputation: 545

Override OnShutdown is the correct method. OnStop is not called during shutdown.

Microsoft Windows has added an option called Fast Startup which does not actually shutdown the computer.

As noted in the Fast Startup setting description, Restart isn't affected. This is why the Restart triggers OnShutdown and Shutdown does not.

Turning off Fast Startup will trigger OnShutdown for both Restart and Shutdown.

Power Options System Settings

Upvotes: 6

Related Questions