我陷入了必须从网址列表中下载多个文件的情况。我发现Parallel.ForEach
是一个解决方案,它确实比简单的foreach更快。但是这个解决方案不等待直到所有下载完成。
List<string> list = new List<string>() {"url1","url2","url3",... };
public async void downloadSimpleFile(string fileUrl) {
//download file logic
}
await Task.Factory.StartNew(() => Parallel.ForEach(list,
new ParallelOptions { MaxDegreeOfParallelism = 10 }, downloadSimpleFile));
我也在追赶:
public async Task<bool> downloadSimpleFile(string fileUrl) {
//download file logic
return true;
}
现在我如何在downloadSimpleFile
中使用Parallel.ForEach
,因为上述代码不再有用了?
答案 0 :(得分:3)
使用Task.WhenAll方法。以下代码应该有效:
public async Task<bool> downloadSimpleFile(string fileUrl)
{
//download file logic
return true;
}
public async Task ProcessList()
{
var list = new List<string> {"url1", "url2", "url3" };
var downloadFiles = list.Select(downloadSimpleFile).ToArray();
var result = await Task.WhenAll(downloadFiles);
}