我从文件中获得了几个文件链接到循环语句,对于每个链接,我必须下载文件,下载完成后我必须对每个文件做一些事情。
这是我的代码,
foreach(//condition ) {
Descarcare = new WebClient();
Descarcare.DownloadProgressChanged += Descarcare_DownloadProgressChanged;
Descarcare.DownloadFileAsync(new Uri(nod.SelectSingleNode("DownloadLink").InnerText), Directory.GetCurrentDirectory()+);
Descarcare.DownloadFileCompleted +=Descarcare_DownloadFileCompleted;
}
void Descarcare_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
//extract the file
}
但不知何故,webclient下载文件,但DownloadFileCompleted事件仅针对上次下载的文件触发,而不是针对每个文件执行。
导致这种情况的原因是什么?
答案 0 :(得分:0)
您正在WebClient
- 循环的每次迭代中创建新的foreach
。最好的方法是创建一个包含所有文件的Queue,并在每个DownloadFileCompleted中开始新的下载,直到获得所需的所有文件。
var _downloadQueue = new Queue<Uri>();
var _webClient = new WebClient();
//in your constructor:
_webClient.DownloadProgressChanged += Descarcare_DownloadProgressChanged;
_webClient.DownloadFileCompleted += Descarcare_DownloadFileCompleted;
private void Foo()
{
//...
foreach(/* condition */)
{
_downloadQueue.Enqueue(
new Uri(nod.SelectSingleNode("DownloadLink").InnerText)
);
}
DownloadNext();
}
private void DownloadNext()
{
if(_downloadQeue.Count> 0)
{
_webClient.DownloadFileAsync(
_downloadQueue.Dequeue(), Directory.GetCurrentDirectory()
);
}
}
void Descarcare_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
DownloadNext();
//extract the file
//...
}