So ServiceController.WaitForStatus https://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.waitforstatus.aspx是一个阻塞调用。如何以任务/异步方式完成?
代码为ServiceController.WaitForStatus
is:
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();
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)