Search code examples
c#servicecontroller

Do you know any alternatives to ServiceController class (C#)


The problem is that we don't have a way to 'cancel' a slow/never starting service once we attempted to start it, if its taking too long:

 ServiceController ssc = new ServiceController(serviceName);
 ssc.Start();
 ssc.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(ts)));

Lets Say we set 'ts' to be something way too long like 300 seconds and after waiting for 120 I decide to cancel the operation, I don't want to wait for the Service controller status to change or wait for the time out to occur, how can I do that?


Solution

  • You can write your own WaitForStatus function that takes in a CancellationToken to get the cancel functionality.

    public void WaitForStatus(ServiceController sc, ServiceControllerStatus statusToWaitFor,
        TimeSpan timeout, CancellationToken ct)
    {
        var endTime = DateTime.Now + timeout;
        while(!ct.IsCancellationRequested && DateTime.Now < endTime)
        {
             sc.Refresh();
             if(sc.Status == statusToWaitFor)
                 return;
    
             // may want add a delay here to keep from
             // pounding the CPU while waiting for status
        }
    
        if(ct.IsCancellationRequested)
        { /* cancel occurred */ }
        else
        { /* timeout occurred */ }
     }