10

所以ServiceController.WaitForStatus是一个阻塞调用。怎样才能做到Task/Async的方式呢?

4

1 回答 1

17

的代码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();
        }
    }
}
于 2016-07-07T01:15:38.083 回答