1

I'm using ServiceController to restart windows server. Here is my C# code.

ServiceController service = new ServiceController("ServiceName");   
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, 15000);
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, 15000);

I works great on my local machine, if service "ServiceName" does not exist it throws exception and this is ok.
But on the server there I need this code to be running if service with "ServiceName" does not exist I do not get any exceptions and the code just stuck here:

service.Stop();

and it waits forever... As a result I can't catch this, I can't do anything it just stuck.
Can anybody help me?

Mat
  • 202,337
  • 40
  • 393
  • 406
Vladimir
  • 11
  • 2

1 Answers1

1

Instead of relying on an exception if your code can't find the service how about this:

    ServiceController service = ServiceController.GetServices()
        .Where(s => s.ServiceName == "ServiceName")
        .SingleOrDefault();

    if (service != null)
    {
        service.Stop();
        service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(15));
        service.Start();
        service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(15));
    }
    else
    {
        // Couldn't find service
    }

NOTE: I had to change the ServiceControllerStatus.WaitForStaus signature to use a timespan

Mike
  • 661
  • 5
  • 10
  • 1
    As a matter of fact I need following: `ServiceController service = ServiceController.GetServices("MachineName") .Where(s => s.ServiceName == "ServiceName") .SingleOrDefault();` and if "MachineName" does not exist it stuck here – Vladimir Apr 14 '11 at 14:35
  • The MachineName overload is used if you're trying to control services on a different machine from the executing code. If you need to include the machine name I'm guessing you're trying to control services on a separate machine, does the user who's executing the code have access to the machine in question? – Mike Apr 14 '11 at 15:00
  • He doesn't. But, I think, in this case I should get an exception (i do get exception locally) But on the remote server, there this code is supposed to be running, I do not get any exceptions :(. – Vladimir Apr 18 '11 at 07:10