Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stop windows service in onStart() method

I want to stop windows service in onStart() method when customer doesn't have a license. I use service.Stop(), but it does not work.

protected override void OnStart(string[] args)
{
    try
    {
        _bridgeServiceEventLog.WriteEntry("new OnStart");
        if (LicenseValidetor.ValidCountAndTypeDevices())
        {
            WsInitializeBridge();
        }
        else
        {
            service = new ServiceController("BridgeService");
            service.Stop();
            _bridgeServiceEventLog.WriteEntry("LicenseValidetor Error");
        }
        _bridgeServiceEventLog.WriteEntry("end Start");
    }
    catch (Exception e)
    {
        _bridgeServiceEventLog.WriteEntry("error In onstart method ");
    }

}
like image 206
Tarek Saied Avatar asked Aug 22 '12 07:08

Tarek Saied


1 Answers

You cannot stop a service from within the OnStart method of that same service.

The ServiceController.Stop method internally calls ControlService (or it's Ex counterpart). Notice that one of the reasons that this function can fail is:

ERROR_SERVICE_CANNOT_ACCEPT_CTRL The requested control code cannot be sent to the service because the state of the service is SERVICE_STOPPED, SERVICE_START_PENDING, or SERVICE_STOP_PENDING.

Well, guess what - when you're inside your OnStart method, the state of your service is SERVICE_START_PENDING.


The correct way to cope with this situation is to signal any other threads that you may have started to have them exit, and then to exit your OnStart method. The service control manager will notice that the process has exited and revert your service status to SERVICE_STOPPED. It may also notify an interactive user that "The service started and then stopped" or words to that effect.

like image 136
Damien_The_Unbeliever Avatar answered Oct 11 '22 13:10

Damien_The_Unbeliever