当电脑关机进入挂起模式时,我需要停止我们的 Windows 服务,并在电脑再次恢复时重新启动它。这样做的正确方法是什么?
问问题
4919 次
4 回答
8
您应该覆盖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;
}
于 2013-05-16T16:59:26.440 回答
3
评论 Alex Filipovici 答案于 2013 年 5 月 16 日 17:05 编辑:
CanHandlePowerEvent = true;
必须在构造函数中设置
设置它OnStart()
为时已晚并导致此异常:
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)
于 2017-05-01T17:45:10.433 回答
0
这是 Windows 服务的功能之一。
关闭
PC 关机时自动关机。无需做任何事情。要进行任何清理,您需要覆盖ServiceBase
类型方法,例如OnPowerEvent
,示例
public class WinService : ServiceBase
{
protected override void OnStart(string[] args)
{
...
}
protected override void OnStop()
{
...
}
protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus)
{
...
}
}
开始
要自动启动服务,您需要将其设置为ServiceStartMode.Automatic
like here
[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, // <<<HERE
Description = "Foo service"
};
Installers.Add(_process);
Installers.Add(_service);
}
}
于 2013-05-16T16:52:46.013 回答
0
您可以简单地停止处理,而不是停止您的服务,例如......
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)
{
}
}
于 2013-05-16T16:54:45.207 回答