超时已过期且操作管理器中尚未完成操作

时间:2013-11-04 19:32:26

标签: c# .net windows-services

我有一个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
            }
        }
    }

2 个答案:

答案 0 :(得分:2)

问题在于:

service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);

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

答案 1 :(得分:2)

您也可以尝试打开

  

"事件查看器" - > " Windows日志" - > "用途"

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