我正在编写一个使用ServiceController以编程方式启动/停止Windows服务的应用程序。我有一个UI类,它有一些UI花哨,还有一个Helper类,它可以启动和停止服务。
在Helper类中:
void StopService()
{
var controller = new ServiceController("MyService");
if (controller.Status == ServiceControllerStatus.Running)
{
controller.Stop();
controller.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 60));
}
}在UI类中:
Helper.StopService();
var controller = new ServiceController("MyService");
if (controller.Status == ServiceControllerStatus.Stopped)
{
// Do some stuff
}
else
{
// MyService not stopped. Explode!
}问题是当服务停止时,Helper中的方法立即返回到UI类中的调用者,而不等待服务到达停止(服务最终在大约5-10秒后停止)。如果我将启动/停止逻辑移到UI类,事情就变得正常了。
我在这里犯了什么愚蠢的错误?
发布于 2016-07-16 03:16:56
您可以使用延迟/刷新循环代替ServiceController.WaitForStatus(),如ServiceController Class中的MSDN所示,但更好的方法可能是使用异步等待状态,如this answer中详细介绍的那样。
sc.Stop();
while (sc.Status != ServiceControllerStatus.Stopped)
{
Thread.Sleep(1000);
sc.Refresh();
}https://stackoverflow.com/questions/30996720
复制相似问题