I try to update a progress bar while awaiting a async IO operation. The following code is doing that.
Task<string> io = SomeOperationAsync();
while(!io.IsComplete)
{
progressBar.Value = value // add some progress;
await Task.Delay(TimeSpan.FromMilliseconds(200));
}
string result = await io;
This works quite ok.The Progressbar fills up quite smoothly.
But as you see, I will check for completion every 200 ms rather than really awaiting it. I might end up waiting for up to 200 ms too long.
Is there a better way to achieve this, so that my method can immediately return once the IO operation is complete?
>Solution :
You can use .WhenAny() to return when any task completes. A small refactor to your code would return if the primary task finishes before the delay.
Task<string> io = SomeOperationAsync();
while(!io.IsComplete)
{
progressBar.Value = value // add some progress;
await Task.WhenAny(io, Task.Delay(TimeSpan.FromMilliseconds(200)));
}
string result = await io;