1

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?

safejrz
  • 544
  • 1
  • 14
  • 26

1 Answers1

3

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 */ }
 }
JG in SD
  • 5,427
  • 3
  • 34
  • 46
  • I however have one question on your code from above, iiuc it is extending the ServiceController class, then why pass an instance of ServiceController, Unless I'm missing something, shouldn't we reference the properties of the object itself ('this') instead of passing a reference? – safejrz Jan 10 '13 at 14:11
  • @safejrz The way I wrote it allows you to put the function wherever you want. You could make a derived from `ServiceController` -- in which case yes you wouldn't need to pass in the `ServiceController`, you could also make it an extension method by using the `this` modifier on the `ServiceController`, or you could put it as a static method in the class that needs the code. Its all up to you and what works best for you, your team, and your code base. – JG in SD Jan 10 '13 at 15:38