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
IProgress<T> InterfaceDefines a provider for progress updates.
C# Language Async-Await Async/await will only improve performance if it allows the machine to do additional work.
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 ...)); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With