【问题标题】:How to do progress reporting using Async/Await如何使用 Async/Await 进行进度报告
【发布时间】:2020-10-20 10:39:14
【问题描述】:

假设我有一个文件列表,我必须使用 c# 项目中的 ftp 相关类将其复制到 Web 服务器。在这里,我想使用 Async/Await 功能,并且还想同时显示多个文件上传的多个进度条。每个进度条指示每个文件的上传状态。所以请指导我如何做到这一点。

当我们与后台工作人员一起做这种工作时,这很容易,因为后台工作人员有进度更改事件。那么如何使用 Async/Await 来处理这种情况。如果可能的话,用示例代码指导我。谢谢

【问题讨论】:

标签: c# async-await


【解决方案1】:

来自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));
}

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

【讨论】:

  • 您的代码没问题,但我如何使用 status.need 指南显示多个文件上传的多个进度条。谢谢
  • @Thomas 您的 UploadAndProcessAsync 本身应该遵循相同的模式并具有 IProgress&lt;T&gt; progress 参数。
  • 不是很清楚。如果您给我宝贵的时间来完成代码,那将非常有帮助。假设 imageList 有 3 个文件名,我想为此显示三个进度条。所以请指导我如何添加 3 个进度条并从 UploadPicturesAsync() 函数更新进度条状态。我不知道什么是 IProgress 以及它是如何工作的。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-23
  • 1970-01-01
  • 1970-01-01
  • 2018-06-04
  • 2016-12-04
  • 2012-12-02
  • 2018-10-11
相关资源
最近更新 更多