1

问题是,一旦我们尝试启动它,我们没有办法“取消”一个缓慢/永不启动的服务,如果它花费太长时间:

 ServiceController ssc = new ServiceController(serviceName);
 ssc.Start();
 ssc.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(ts)));

假设我们将“ts”设置为太长,例如 300 秒,在等待 120 秒后我决定取消操作,我不想等待服务控制器状态更改或等待超时发生, 我怎样才能做到这一点?

4

1 回答 1

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 */ }
 }
于 2013-01-09T21:57:12.110 回答