Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

c# - 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. 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...