如何做一个异步ServiceController.WaitForStatus?

时间:2016-07-07 01:15:38

标签: .net async-await task servicecontroller

所以ServiceController.WaitForStatus是阻止通话。如何完成任务/异步方式?

1 个答案:

答案 0 :(得分:9)

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();
        }
    }
}