[英]Windows Service OnStop when computer shutdown
I'm writing a Windows Service in C#.我正在用 C# 编写 Windows 服务。 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?我是否必须覆盖ServiceBase.OnShutdown()
,或者覆盖ServiceBase.OnStop()
两种情况就足够了?
Yes.是的。 OnStop()
gets called when the machine is shutdown. OnStop()
在机器关闭时被调用。 OnShutdown()
is for when you need to know specifically that the machine is being shutdown. OnShutdown()
用于当您需要特别知道机器正在关闭时。
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.所以你的代码应该假设在机器关闭时可能会或可能不会调用OnStop()
。 If you need to clean up during a shutdown, handle OnShutdown()
.如果您需要在关机期间进行清理,请处理OnShutdown()
。
Override OnShutdown
is the correct method.覆盖OnShutdown
是正确的方法。 OnStop
is not called during shutdown.在关机期间不调用OnStop
。
Microsoft Windows has added an option called Fast Startup
which does not actually shutdown the computer. Microsoft Windows 添加了一个名为“ Fast Startup
的选项,它实际上不会关闭计算机。
As noted in the Fast Startup
setting description, Restart
isn't affected.如Fast Startup
设置说明中所述, Restart
不受影响。 This is why the Restart
triggers OnShutdown
and Shutdown
does not.这就是为什么Restart
会触发OnShutdown
而Shutdown
不会。
Turning off Fast Startup
will trigger OnShutdown
for both Restart
and Shutdown
.关闭Fast Startup
将触发Restart
和Shutdown
OnShutdown
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.