是否确定做一些异步/等待里面的一些.NET Parallel.ForEach()code? [英] Is it OK to do some async/await inside some .NET Parallel.ForEach() code?
问题描述
由于以下code,是它的确定的办异步/计谋
在 Parallel.ForEach
?
Given the following code, is it OK to do async/await
inside a Parallel.ForEach
?
如:
Parallel.ForEach(names, name =>
{
// Do some stuff...
var foo = await GetStuffFrom3rdPartyAsync(name);
// Do some more stuff, with the foo.
});
或者是有一些疑难杂症的,我必须意识到的?
or is there some gotcha's that I need to be made aware of?
编辑:不知道,如果这个编译,顺便说一句。只是Pseduo- code ..想出声来。
No idea if this compiles, btw. Just Pseduo-code .. thinking out loud.
推荐答案
没有,这是没有意义的结合异步
与 Paralell。的foreach
。
No, It doesn't make sense to combine async
with Paralell.Foreach
.
请看下面的例子:
private void DoSomething()
{
var names = Enumerable.Range(0,10).Select(x=> "Somename" + x);
Parallel.ForEach(names, async(name) =>
{
await Task.Delay(1000);
Console.WriteLine("Name {0} completed",name);
});
Console.WriteLine("Parallel ForEach completed");
}
输出什么,你会期待什么呢?
What output you will expect?
Name Somename3 completed
Name Somename8 completed
Name Somename4 completed
...
Parallel ForEach completed
这是不是会发生什么。这将输出:
That's not what will happen. It will output :
Parallel ForEach completed
Name Somename3 completed
Name Somename8 completed
Name Somename4 completed
...
为什么呢?因为当的ForEach
第一打等待
的方法实际上返回, Parallel.ForEach
不知道它是异步的,它运行完成!之后,code 等待
运行为继续在另一个线程的不可以Paralell处理线程
Why? Because when ForEach
hits first await
the method actually returns, Parallel.ForEach
doesn't know it is asynchronous and it ran to completion!. Code after await
runs as continuation on another thread not "Paralell processing thread"
这篇关于是否确定做一些异步/等待里面的一些.NET Parallel.ForEach()code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!