暂停/恢复PC时,使Windows服务停止并正常启动的正确方法是什么?
我需要在PC关机进入挂起模式时停止我们的Windows服务,并在PC再次恢复时重新启动它。 这样做的正确方法是什么?
您应该重写ServiceBase.OnPowerEvent方法 。
protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus) { if (powerStatus.HasFlag(PowerBroadcastStatus.QuerySuspend)) { } if (powerStatus.HasFlag(PowerBroadcastStatus.ResumeSuspend)) { } return base.OnPowerEvent(powerStatus); }
PowerBroadcastStatus枚举解释了电源状态。 此外,您还需要将ServiceBase.CanHandlePowerEvent属性设置为true
。
protected override void OnStart(string[] args) { this.CanHandlePowerEvent = true; }
评论Alex Filipovici答案编辑于2013年5月16日17:05:
CanHandlePowerEvent = true;
必须在构造函数中设置
在OnStart()
设置它为时已晚并导致此exception:
Service cannot be started. System.InvalidOperationException: Cannot change CanStop, CanPauseAndContinue, CanShutdown, CanHandlePowerEvent, or CanHandleSessionChangeEvent property values after the service has been started. at System.ServiceProcess.ServiceBase.set_CanHandlePowerEvent(Boolean value) at foo.bar.OnStart(String[] args) at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state)
您可以简单地停止处理,而不是停止您的服务…
Microsoft.Win32.SystemEvents.PowerModeChanged += this.SystemEvents_PowerModeChanged; private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e) { if (e.Mode == PowerModes.Suspend) { } if (e.Mode == PowerModes.Resume) { } }
这是Windows服务的function之一。
关掉
关闭PC时自动关闭。 无需做任何事情。 要进行任何清理,您需要覆盖ServiceBase
类型的方法,如OnPowerEvent
,sample
public class WinService : ServiceBase { protected override void OnStart(string[] args) { ... } protected override void OnStop() { ... } protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus) { ... } }
开始
要自动启动服务,您需要将其设置为ServiceStartMode.Automatic
就像这里一样
[RunInstaller(true)] public class WindowsServiceInstaller : Installer { private readonly ServiceProcessInstaller _process; private readonly ServiceInstaller _service; public WindowsServiceInstaller() { _process = new ServiceProcessInstaller { Account = ServiceAccount.LocalSystem }; _service = new ServiceInstaller { ServiceName = "FOO", StartType = ServiceStartMode.Automatic, // <<