gio*_*efj 4 .net c# task-parallel-library async-await
我有这个代码:
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");
Run Code Online (Sandbox Code Playgroud)
它应该处理超过800个元素的列表,但它不等待下载和文件写入完成.事实上,他开始下载和写作,显示消息,然后在后台继续下载...我需要下载很多文件并行和异步,但我必须等待所有这些文件下载.这段代码出了什么问题?
Parallel.ForEach
不适用于异步.它期望一个Action
但是为了等待它需要的异步方法Func<Task>
.
您可以使用ActionBlock
以异步构建的TPL Dataflow 代替.你给它一个委托(异或非)来对每个项目执行.您可以配置块的并行性(如果需要,还可以配置有界容量).并将您的商品发布到其中:
var block = new ActionBlock<string>(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);
}
}
}, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 2 } );
foreach (var url in urls)
{
block.Post(url);
}
block.Complete();
await block.Completion;
// done
Run Code Online (Sandbox Code Playgroud)