C# – How to do progress reporting using Async/Await

async-awaitc

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

Best Answer

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 ...));
}