When the Windows operating system shutdown, the method does not perform OnStop Windows Service's (reprint)

Windows Service OnStop when computer shutdown

 

 

ask:


 

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?

 

 

answer:


 

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.

 

 

So in fact, when the Windows operating system shutdown, calls are ServiceBase.OnShutdown () method, while ServiceBase.OnStop () method will not be called, but to be safe, I recommend and implement in OnStop OnShutdown methods Windows Service to stop logic, in addition we add a lock variable and a flag variable in OnStop and OnShutdown method, so that if a method to stop the execution logic of Windows Service, another method would not stop the execution logic of the Windows Service.

 

Also note that the Windows operating system shutdown, only to ServiceBase.OnShutdown () method execution time of 12 seconds, more than this time Windows Service process will still be forced to terminate, you can refer to this article , use PreShutdown event the timeout period extended to 3 minutes.

 

In addition, after testing, DasMulli.Win32.ServiceUtils the .NET Core in Windows Service Framework has a flaw in the Windows operating system shutdown, and does not call its IWin32Service.Stop () method, so there is a big security risk, please carefully use.

 

 

Description link

 

Guess you like

Origin www.cnblogs.com/OpenCoder/p/11544805.html