. Net – how to make an asynchronous servicecontroller WaitForStatus?
•
Java
So servicecontroller Waitforstatus is a blocked call How can I complete the task / asynchronously?
Solution
ServiceController. The code of 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();
}
}
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();
}
}
}
Or cancellationtoken is supported
public static class ServiceControllerExtensions
{
public static async Task WaitForStatusAsync(this ServiceController controller,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();
}
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
