问题是,一旦我们试图启动它,我们就没有办法“取消”缓慢/永不启动的服务,如果它花了太长时间:
ServiceController ssc = new ServiceController(serviceName);
ssc.Start();
ssc.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(ts)));
让我们说'ts'设置得太长,比如300秒,等待120后我决定取消操作,我不想等待服务控制器状态改变或等待时间要发生这种情况,我该怎么做?
答案 0 :(得分:3)
您可以编写自己的WaitForStatus函数,该函数接收CancellationToken
以获取取消功能。
public void WaitForStatus(ServiceController sc, ServiceControllerStatus statusToWaitFor,
TimeSpan timeout, CancellationToken ct)
{
var endTime = DateTime.Now + timeout;
while(!ct.IsCancellationRequested && DateTime.Now < endTime)
{
sc.Refresh();
if(sc.Status == statusToWaitFor)
return;
// may want add a delay here to keep from
// pounding the CPU while waiting for status
}
if(ct.IsCancellationRequested)
{ /* cancel occurred */ }
else
{ /* timeout occurred */ }
}