I'm using ServiceController to restart windows server. Here is my C# code.
ServiceC开发者_如何学Pythonontroller 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:
    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
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论