當Windows操做系統關機時,不會執行Windows Service的OnStop方法(轉載)

Windows Service OnStop when computer shutdownhtml

 

 

問:windows


 

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?框架

 

 

答:ide


 

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.atom

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

Turning off Fast Startup will trigger OnShutdown for both Restart and Shutdown.操作系統

 

 

因此實際上,在Windows操做系統關機時,會調用的是ServiceBase.OnShutdown()方法(前提是設置了ServiceBase類的CanShutdown屬性爲true),而ServiceBase.OnStop()方法並不會被調用,可是爲了安全起見,我建議在OnStop和OnShutdown方法中都實現Windows Service的中止邏輯,此外咱們在OnStop和OnShutdown方法中使用一個鎖變量和一個標誌變量,使得若是一個方法先執行了Windows Service的中止邏輯,另外一個方法就不會執行Windows Service的中止邏輯了。htm

 

此外須要注意的是Windows操做系統在關機時,只會給ServiceBase.OnShutdown()方法12秒的執行時間,超過這個時間後Windows Service的進程仍是會被強制終止,能夠參照這篇文章,使用PreShutdown事件將超時時間擴展爲3分鐘。

 

另外,通過測試,DasMulli.Win32.ServiceUtils這個.NET Core的Windows Service框架也有缺陷,在Windows操做系統關機時,並不會調用其IWin32Service.Stop()方法,因此存在很大的安全隱患,請慎用。

 

 

原文連接

相關文章
相關標籤/搜索