你知道ServiceController类的任何替代品(C#)

时间:2013-01-09 21:43:49

标签: c# servicecontroller

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

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

让我们说'ts'设置得太长,比如300秒,等待120后我决定取消操作,我不想等待服务控制器状态改变或等待时间要发生这种情况,我该怎么做?

1 个答案:

答案 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 */ }
 }