假设我有一个文件列表,我必须使用c#project中的ftp相关类复制到Web服务器。在这里我想使用Async / Await功能,并且还希望同时显示多个文件上传的多个进度条。每个进度条指示每个文件上载状态。所以指导我如何做到这一点。
当我们与后台工作人员合作完成这类工作时,这很容易,因为后台工作人员有进度变更事件。那么如何使用Async / Await处理这种情况。如果可能的话,用示例代码指导我。感谢
答案 0 :(得分:32)
来自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 async Task<int> 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 ...));
}