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 ...));
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…