How to do progress reporting using Async/Await

前端 未结 1 1644
忘了有多久
忘了有多久 2020-12-08 10:32

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 multi

相关标签:
1条回答
  • 2020-12-08 10:50

    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 ...));
    }
    
    0 讨论(0)
提交回复
热议问题