我有一个从服务器下载文件的URL集合列表。
foreach (var category in jsonCollection.Categories)
{
lblFileName.Text = category.File_name; //Here i want to show a message which file is downloading
Thread thread = new Thread(() => {
WebClient client = new WebClient();
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
client.DownloadFileAsync(new Uri(category.Url), @"G:\PROJECT\BCCP\file_name");
});
thread.Start();
}
我知道DownloadFileCompleted处理程序将在完成每个下载的文件后调用。但我需要一个在文件下载过程中触发的事件,这样我就可以显示正在下载哪个文件的消息。这里的循环只是完成循环,然后DownloadFileAsync异步完成任务。
使用await关键字。等待运算符应用于异步方法中的任务,以在方法的执行中插入挂起点,直到等待的任务完成。
await client.DownloadFileTaskAsync(new Uri("download_url"), "location_url_where_do_you_want_to_download");
//Do anything what do you want...
必须在函数名称之前添加async关键字。
我找到了我的解决方案。使用await关键字,使函数异步,并使用DownloadFileTaskAsync
private async void functionName()
{
foreach (var category in jsonCollection.Categories)
{
Thread thread = new Thread(() => {
WebClient client = new WebClient();
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
await client.DownloadFileTaskAsync(new Uri(category.Url), @"G:\PROJECT\BCCP\file_name");
//await for downloading
lblFileName.Text = category.File_name;
});
thread.Start();
}
}