What is the proper way to have a Windows service stop and start gracefully when suspending/resuming a PC?

5.8k Views Asked by At

I need to stop our Windows service when a PC is powered down into Suspend mode and restart it when the PC is resumed again. What is the proper way to do this?

4

There are 4 best solutions below

3
Alex Filipovici On BEST ANSWER

You should override the ServiceBase.OnPowerEvent Method.

protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus)
{
    if (powerStatus.HasFlag(PowerBroadcastStatus.QuerySuspend))
    { 

    }

    if (powerStatus.HasFlag(PowerBroadcastStatus.ResumeSuspend))
    {

    }
    return base.OnPowerEvent(powerStatus);
}

The PowerBroadcastStatus Enumeration explains the power statuses. Also, you'll need to set the ServiceBase.CanHandlePowerEvent Property to true.

protected override void OnStart(string[] args)
{
    this.CanHandlePowerEvent = true;
}
1
oleksii On

That's one of the features of Windows service.

Shutdown

The shutdown is done automatically when PC is shut down. No need to do anything. To do any clean up you would need to override ServiceBase type methods like OnPowerEvent, sample

public class WinService : ServiceBase
{
    protected override void OnStart(string[] args)
    {
        ...
    }

    protected override void OnStop()
    {
        ...
    }

    protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus)
    {
            ...
    }
}

Start

To start a service automatically you need to set it to 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);
    }
}
4
user2315985 On

Instead of stopping your service could you simply stop the processing with something like...

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)
            {

            }
    }
0
Markus On

Comment on Alex Filipovici Answer edited May 16 '13 at 17:05:

CanHandlePowerEvent = true; 

must be set in the constructor

Setting it in OnStart() is too late and causes this 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)