2016-07-07 16 views

答えて

7

ServiceController.WaitForStatusためのコードは次のとおり

public void WaitForStatus(ServiceControllerStatus desiredStatus, TimeSpan timeout) 
{ 
    DateTime utcNow = DateTime.UtcNow; 
    this.Refresh(); 
    while (this.Status != desiredStatus) 
    { 
     if (DateTime.UtcNow - utcNow > timeout) 
     { 
      throw new TimeoutException(Res.GetString("Timeout")); 
     } 
     Thread.Sleep(250); 
     this.Refresh(); 
    } 
} 

これは以下を使用してタスクベースのAPIに変換することができる。

public static class ServiceControllerExtensions 
{ 
    public static async Task WaitForStatusAsync(this ServiceController controller, ServiceControllerStatus desiredStatus, TimeSpan timeout) 
    { 
     var utcNow = DateTime.UtcNow; 
     controller.Refresh(); 
     while (controller.Status != desiredStatus) 
     { 
      if (DateTime.UtcNow - utcNow > timeout) 
      { 
       throw new TimeoutException($"Failed to wait for '{controller.ServiceName}' to change status to '{desiredStatus}'."); 
      } 
      await Task.Delay(250) 
       .ConfigureAwait(false); 
      controller.Refresh(); 
     } 
    } 
} 

またはCancellationToken

public static class ServiceControllerExtensions 
{ 
    public static async Task WaitForStatusAsync(this ServiceController controller, ServiceControllerStatus desiredStatus, TimeSpan timeout, CancellationToken cancellationToken) 
    { 
     var utcNow = DateTime.UtcNow; 
     controller.Refresh(); 
     while (controller.Status != desiredStatus) 
     { 
      if (DateTime.UtcNow - utcNow > timeout) 
      { 
       throw new TimeoutException($"Failed to wait for '{controller.ServiceName}' to change status to '{desiredStatus}'."); 
      } 
      await Task.Delay(250, cancellationToken) 
       .ConfigureAwait(false); 
      controller.Refresh(); 
     } 
    } 
} 
をサポートします
関連する問題