0

I am using the following function to stop my windows service (with a timeout):

public int StopService()
{
    ServiceController service = new ServiceController(serviceName);
    try
    {
        TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
        service.Stop();
        service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);              
        return 1;
    }
    catch (Exception ex)
    {
        logger.Log(LoggingLevel.Error,
                this.GetType().Name + ":" + MethodBase.GetCurrentMethod().Name,
                string.Format("{0}", ex.Message));
        return -1;
    }
}

I check the status of the service. And if it is not ServiceControllerStatus.Stopped I call this function. I have tested and the program works when the status of the server is Running or Stopped. But I would like to know what happens when the status is other states such as StopPending, StartPending, etc. If I tell my service to stop while the state is one of the above, will the Stop command still do its job?

disasterkid
  • 6,948
  • 25
  • 94
  • 179

2 Answers2

1

It depends on the service and what it permits at the time of the call to Stop().

At the Win32 level, each service must regularly call SetServiceStatus() to inform the Service Control Manager (SCM) what commands it will accept. Your call to Stop() will only succeed when the service has explicitly said that it allows that operation. In my experience, services in a pending state do not usually allow the normal range of operations so a call to Stop() will likely fail.

Note that it is easy to check what is permitted in C#, as illustrated in this sample code under the Examples heading. You can prefix your call to Stop() with CanStop(), and maybe wait a while if the service isn't quite ready to be stopped yet. Contingencies abound.

CoreTech
  • 2,345
  • 2
  • 17
  • 24
0

You can try like below, below example for StopPending ,

while (service.Status == ServiceControllerStatus.StopPending) //If it is stop pending, wait for it
                {
                    System.Threading.Thread.Sleep(30 * 1000); //  thread sleep for 30 seconds
                    service.Refresh(); // refreshing status

                    if (service.Status == ServiceControllerStatus.Stopped)
                    {
                        Comments = "Service " + serviceName + " stopped successfully. ";

                    }
                }

Let me know whether it works or not. Please also provide if you have(had) any better solution