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?
Instead of relying on an exception if your code can't find the service how about this:
NOTE: I had to change the ServiceControllerStatus.WaitForStaus signature to use a timespan