1

問題は、サービスを開始しようとすると、時間がかかりすぎる場合に、開始が遅い/開始されないサービスを「キャンセル」する方法がないことです。

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

「ts」を 300 秒のように長すぎるように設定し、120 秒待った後、操作をキャンセルすることにしたとします。サービス コントローラーのステータスが変化するのを待つか、タイムアウトが発生するのを待ちたくありません。 、 どうやってやるの?

4

1 に答える 1

3

CancellationTokenキャンセル機能を取得する独自の WaitForStatus 関数を作成できます。

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 に答える