关于C ++:异步停止Windows服务

Stopping Windows service asynchronously

我正在尝试控制应用程序内的服务。 通过StartService(MSDN)启动服务工作正常,该服务大约需要10秒钟才能启动,但是在调用StartService之后,它将立即将控件交还给主应用程序。

但是,通过ControlService(MSDN)-AFAIK停止服务时,没有StopService-它会阻止主应用程序完整的时间,直到服务停止为止,这大约需要10秒钟。

1
2
Start: StartServiceW( handle, 0, NULL)
Stop: ControlService( handle, SERVICE_CONTROL_STOP, status )

有没有办法非阻塞/异步停止Windows服务?


该服务正在其控制处理程序例程中进行清理。对于只需要一秒钟的时间退出的服务来说,这是可以的,但是将要花费十秒钟的服务肯定应该将状态设置为STOP_PENDING,然后异步进行清理。

如果这是您自己的服务,则应纠正此问题。我首先要确保所有清理工作都是确实有必要的;例如,无需在停止之前释放内存(除非该服务与其他服务共享进程)。如果清理的速度确实不够快,请启动一个单独的线程(或向您的主线程发送信号)以执行服务关闭并将服务状态设置为STOP_PENDING。

如果这是其他人的服务,唯一的解决方案是从单独的线程或子流程中发出停止请求。


SCM以串行方式处理控制请求。如果任何服务正忙于处理控制请求,则ControlService()将被阻止,直到SCM可以处理新请求为止。在文档中对此进行了详细说明:

The SCM processes service control notifications in a serial fashion—it
will wait for one service to complete processing a service control
notification before sending the next one. Because of this, a call to
ControlService will block for 30 seconds if any service is busy
handling a control code. If the busy service still has not returned
from its handler function when the timeout expires, ControlService
fails with ERROR_SERVICE_REQUEST_TIMEOUT.


我可能会考虑在新线程中停止服务。那将消除主线程的阻塞。