Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 915
Bender the Greatest Avatar asked May 16 '13 16:05

Bender the Greatest


2 Answers

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;
}
like image 111
Alex Filipovici Avatar answered Sep 19 '22 23:09

Alex Filipovici


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)
like image 34
Markus Avatar answered Sep 21 '22 23:09

Markus