停止 Windows 服务并避免超时警告消息



我已经实现了一个Windows服务,旨在以计划的方式启动业务流程。业务进程启动后,不应通过停止服务来终止它。因此,我使用以下OnStop方法:

    protected override void OnStop()
    {
        /*
         * Check, whether the business process is currently running; 
         */ 
        if (_sh.IsBusinessProcessRunning())
        {
            eventLog1.WriteEntry(String.Format(
                "Stop instruction received! Service will be stopped, as soon the process '{0}' has completed. ", 
                ServiceHelper._businessExecutableName));
        }
        while (_sh.IsBusinessProcessRunning())
        {
            // Check each 30 seconds, whether the business process is still running
            Thread.Sleep(30000);
        }
        eventLog1.WriteEntry("Service stopped!");
    }

实际上这工作正常,除了我收到超时错误对话框,这可能会使客户感到困惑。有没有办法修改此对话框中的消息或避免它被显示?(如果可能的话,我更愿意更新消息)


消息:

服务"..."在"本地主机"上无法终止。服务未及时响应启动或控制请求。

您正在睡眠 30 秒,但 Windows 通常只提供 ~12 秒的时间来关闭服务,因此您很容易超过该时间,这会导致弹出该对话框。

您可以通过调用 ServiceBase.RequestAdditionalTime 来请求增加时间,这应该告诉 SCM 您的服务仍在响应,它只是繁忙。

我也不会在这么大的时间里使用Thread.Sleep。将其减少到几秒钟,无论如何它都在循环中。

最新更新