本文介绍了异步ServiceController.WaitForStatus如何做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So ServiceController.WaitForStatus is a blocking call. How can it be done Task/Async manner?

推荐答案

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:

This can be converted to a task based api using the following:

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

这篇关于异步ServiceController.WaitForStatus如何做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 02:46