i use some code to download mutiple files, which works good. while downloading a lot of files, i would like to be able to cancel them. Besides the UI with a cancel button i use as global variables:
private WebClient client = null;
private CancellationToken cts = new CancellationToken();
Within the download function i use:
// The Object SourceId is only used to be able
// to pass the ID (index) of datasource to callback functions
var current = new SourceId();
current.Id = sourceList.IndexOf(current);
cts = new CancellationToken();
//i tried to use (cancellationToken.Register(() => webClient.CancelAsync())
using (client = new WebClient())
using (cts.Register(() => wc_Cancel()))
{
client.DownloadProgressChanged += wc_DownloadProgressChanged;
client.DownloadFileCompleted += wc_DownloadFileCompleted;
client.DownloadFileAsync(new Uri(driver.Filelink), targetFile, current);
}
"current" is an object, which contains the source ID of the original Datasource, which i use within wc_DownloadProgressChanged and wc_DownloadFileCompleted to determine the correct Data from my datasource.
Within the function wc_DownloadFileCompleted i use if (e.Cancelled) to determine if the download was canceled.
I try to cancel a specific Download. The cancelDownload Function is called by a button after getting the corresponding source Id.
How can i cancel one specificed async download, which means how to pass the needed argument for cancel function ??
private void cancelDownload(int id)
{
// Here i would like to send the ID to cancel to specific download
// and wait for it to finish. How can i do this ?
wc_Cancel();
}
public virtual void wc_Cancel()
{
if (this.client != null)
this.client.CancelAsync();
}
How can i achieve that ?