开发者

ServiceController just get stuck without any exceptions

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜