当Windows操作系统关机时,不会执行Windows Service的OnStop方法(转载)

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?

 

 

答:


 

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.

 

 

所以实际上,在Windows操作系统关机时,会调用的是ServiceBase.OnShutdown()方法(前提是设置了ServiceBase类的CanShutdown属性为true),而ServiceBase.OnStop()方法并不会被调用,但是为了安全起见,我建议在OnStop和OnShutdown方法中都实现Windows Service的停止逻辑,此外我们在OnStop和OnShutdown方法中使用一个锁变量和一个标志变量,使得如果一个方法先执行了Windows Service的停止逻辑,另一个方法就不会执行Windows Service的停止逻辑了。

 

此外需要注意的是Windows操作系统在关机时,只会给ServiceBase.OnShutdown()方法12秒的执行时间,超过这个时间后Windows Service的进程还是会被强制终止,可以参照这篇文章,使用PreShutdown事件将超时时间扩展为3分钟。

 

另外,经过测试,DasMulli.Win32.ServiceUtils这个.NET Core的Windows Service框架也有缺陷,在Windows操作系统关机时,并不会调用其IWin32Service.Stop()方法,所以存在很大的安全隐患,请慎用。

 

 

原文链接

 

转载于:https://www.cnblogs.com/OpenCoder/p/11544805.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值