Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Updating a progress bar while awaiting async operation

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading