How to Report Progress with Async/Await in .NET Core 3

Описание к видео How to Report Progress with Async/Await in .NET Core 3

In this video, we learn how to report progress with async/await in .NET Core 3. If you're using async await, chances are you have long running processes executing on different threads. However, it's very common to update the user on the current progress of that operation in the UI. Maybe you are downloading or uploading files to a server. Perhaps you are copying a number of files from one location to another. Whatever your reason, reporting the progress of an async await process is very easy.

Start by having your method doing the work report the progress using the IProgress(OfT) interface. This interface allows you to report the progress of your method when using async await. It may look something like this:

void LoopThroughNumbers(int count, IProgress(ofInt) progress)
{
for (int x = 0; x (lessthan) count; x++)
{
Thread.Sleep(100);
var percentageComplete = (x * 100) / count;
progress.Report(percentageComplete);
}
}

Now that your method is reporting the progress of its operation, you can now respond to that progress report and display it to the user. Start by creating a new Progress(ofT) object and provide your handler as follows:

var progress = new Progress(ofInt)((value) =(greaterThanBracket)
{
_progressBar.Value = value;
_textBlock.Text = $"{value}%";
});

Once your progress handler is in place, you can now pass this to your method being run in a task to report the progress of your async await method.

await Task.Run(() =(greaterThanBracket) LoopThroughNumbers(100, progress));

That's it!!! You're all done.

Bonus Tip: Don't use Task.Run in the implementation of a method; instead, use Task.Run to call the method.

Check out my new Pluralsight course "Introduction to Prism for WPF":
https://pluralsight.pxf.io/bE3rB

Sponsor Me:
https://github.com/sponsors/brianlagunas

Follow Me:
Twitter:   / brianlagunas  
Twitch:   / brianlagunas  
Blog: http://brianlagunas.com
GitHub: https://github.com/brianlagunas

Комментарии

Информация по комментариям в разработке