【发布时间】:2021-02-17 14:27:28
【问题描述】:
我有一个listOfFilesToDownload。我想并行下载列表中的所有文件
.........
Parallel.ForEach(listOfFilesToDownload, (file) =>
{
SaveFile(file, myModel);
});
private static void SaveFile(string file, MyType myModel)
{
filePath = "...";
try
{
using (WebClient webClient = new WebClient())
{
webClient.DownloadFileTaskAsync(file, filePath)
}
//some time consuming proccess with downloaded file
}
catch (Exception ex)
{
}
}
在SaveFile方法中我下载了文件,然后我想等到下载完,然后对这个文件做一些处理,等到这个处理完成。完整的迭代必须是 - 下载文件并处理它
所以,问题是:
- 如何等到文件以最佳方式下载,所以没有任何东西被阻塞并具有最高性能(我的意思是如果我只使用
DownloadFile,它将阻塞线程直到文件下载,我认为这是不太好) - 如何确保文件已下载,然后才开始处理(因为如果我开始处理不存在的文件或未完全下载的文件,我会遇到错误或错误的数据)
- 如何确保完成对文件的处理(因为我尝试使用
webClient.DownloadFileCompleted事件并在那里处理文件,但我未能确保处理完成,示例如下)
复杂的问题是如何等待文件异步下载并等到它被处理
using (WebClient webClient = new WebClient())
{
webClient.DownloadFileCompleted += DownloadFileCompleted(filePath, myModel);
webClient.DownloadFileTaskAsync(file, filePath);
}
DownloadFileCompleted 返回 AsyncCompletedEventHandler:
public static AsyncCompletedEventHandler DownloadFileCompleted(string filePath, MyType myModel)
{
Action<object, AsyncCompletedEventArgs> action = (sender, e) =>
{
if (e.Error != null)
return;
//some time consuming proccess with downloaded file
};
return new AsyncCompletedEventHandler(action);
}
非常感谢!
【问题讨论】: