【发布时间】:2016-01-18 14:43:58
【问题描述】:
我有这个代码:
await Task.Factory.StartNew(
() => Parallel.ForEach(
urls,
new ParallelOptions { MaxDegreeOfParallelism = 2 },
async url =>
{
Uri uri = new Uri(url);
string filename = System.IO.Path.GetFileName(uri.LocalPath);
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(url))
using (HttpContent content = response.Content)
{
// ... Read the string.
using (var fileStream = new FileStream(config.M_F_P + filename, FileMode.Create, FileAccess.Write))
{
await content.CopyToAsync(fileStream);
}
}
}));
MessageBox.Show("Completed");
它应该处理超过 800 个元素的列表,但它不会等待下载和文件写入完成。 事实上,他开始下载和写作,显示消息,然后在后台继续下载...... 我需要并行和异步下载很多文件,但我必须等待所有文件都下载完毕。这段代码有什么问题?
【问题讨论】:
标签: c# .net async-await task-parallel-library