Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do progress reporting using Async/Await

Tags:

c#

async-await

suppose i have a list of files which i have to copy to web server using ftp related classes in c# project. here i want to use Async/Await feature and also want to show multiple progress bar for multiple file uploading at same time. each progress bar indicate each file upload status. so guide me how can i do this.

when we work with background worker to do this kind of job then it is very easy because background worker has progress change event. so how to handle this kind of situation with Async/Await. if possible guide me with sample code. thanks

like image 396
Thomas Avatar asked Nov 14 '13 14:11

Thomas


People also ask

What is IProgress in C#?

IProgress<T> InterfaceDefines a provider for progress updates.

Does async await improve performance?

C# Language Async-Await Async/await will only improve performance if it allows the machine to do additional work.


1 Answers

Example code with progress from the article

public async Task<int> UploadPicturesAsync(List<Image> imageList,       IProgress<int> progress) {       int totalCount = imageList.Count;       int processCount = await Task.Run<int>(() =>       {           int tempCount = 0;           foreach (var image in imageList)           {               //await the processing and uploading logic here               int processed = await UploadAndProcessAsync(image);               if (progress != null)               {                   progress.Report((tempCount * 100 / totalCount));               }               tempCount++;           }           return tempCount;       });       return processCount; }  private async void Start_Button_Click(object sender, RoutedEventArgs e) {     int uploads=await UploadPicturesAsync(GenerateTestImages(),         new Progress<int>(percent => progressBar1.Value = percent)); } 

If you want to report on each file independently you will have different base type for IProgress:

public Task UploadPicturesAsync(List<Image> imageList,       IProgress<int[]> progress) {       int totalCount = imageList.Count;       var progressCount = Enumerable.Repeat(0, totalCount).ToArray();        return Task.WhenAll( imageList.map( (image, index) =>                            UploadAndProcessAsync(image, (percent) => {            progressCount[index] = percent;           progress?.Report(progressCount);           });                     )); }  private async void Start_Button_Click(object sender, RoutedEventArgs e) {     int uploads=await UploadPicturesAsync(GenerateTestImages(),         new Progress<int[]>(percents => ... do something ...)); } 
like image 111
vittore Avatar answered Sep 20 '22 12:09

vittore