3

我有一个 Windows 服务管理器,我尝试通过管理器停止服务。但是我得到了例外:

Time out has expired and the operation has not been completed

    private static void StopService()
    {
        if (!IsInstalled()) return;
        try
        {
            CFEServiceController c = new CFEServiceController();
            c.StopService(ServiceName, 500);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error in Stop service " + ex.Message);
        }
    }

和:

public void StopService(string serviceName, int timeoutMilliseconds)
    {
        using (ServiceController service = new ServiceController(serviceName))
        {
            try
            {
                TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
                if (service.Status == ServiceControllerStatus.Running)
                {
                    service.Stop();
                    service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
                    Console.WriteLine("Stop service " + serviceName+" ");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error when stop service in code StopService " + ex.Message); // here I got the exception
            }
        }
    }
4

2 回答 2

3

问题是因为这个:

service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);

发生这种情况是因为您的服务并未在您的timeout. 您应该将超时设置得更高,或者根本不设置超时。

于 2013-11-04T19:39:48.153 回答
2

您也可以尝试打开

“事件查看器”->“Windows 日志”->“应用程序”

如果增加/取消设置超时次数没有帮助,则可能有错误级别消息可以为您提供线索,正如@gleng 所回答的那样。

于 2015-01-20T06:07:14.657 回答