简体   繁体   English

如何使用 Async/Await 进行进度报告

[英]How to do progress reporting using Async/Await

suppose i have a list of files which i have to copy to web server using ftp related classes in c# project.假设我有一个文件列表,我必须使用 c# 项目中的 ftp 相关类将其复制到 Web 服务器。 here i want to use Async/Await feature and also want to show multiple progress bar for multiple file uploading at same time.在这里我想使用 Async/Await 功能,还想同时显示多个文件上传的多个进度条。 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.那么如何使用 Async/Await 处理这种情况。 if possible guide me with sample code.如果可能的话,用示例代码指导我。 thanks谢谢

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:如果您想独立报告每个文件,您将拥有不同的 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 ...));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM