Yur*_*rik 9 c# yield-return task-parallel-library async-await c#-5.0
我想使用.NET迭代器和并行Tasks/await?.像这样的东西:
IEnumerable<TDst> Foo<TSrc, TDest>(IEnumerable<TSrc> source)
{
Parallel.ForEach(
source,
s=>
{
// Ordering is NOT important
// items can be yielded as soon as they are done
yield return ExecuteOrDownloadSomething(s);
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是.NET无法原生地处理这个问题.到目前为止@svick的最佳答案 - 使用AsParallel().
奖励:任何实现多个发布者和单个订阅者的简单异步/等待代码?订阅者将屈服,并且pubs将处理.(仅核心库)
svi*_*ick 11
这似乎是PLINQ的工作:
return source.AsParallel().Select(s => ExecuteOrDownloadSomething(s));
Run Code Online (Sandbox Code Playgroud)
这将使用有限数量的线程并行执行委托,并在完成后立即返回每个结果.
如果ExecuteOrDownloadSomething()方法是IO绑定的(例如它实际下载了一些东西)并且你不想浪费线程,那么使用async- await可能有意义,但它会更复杂.
如果你想充分利用async,你不应该返回IEnumerable,因为它是同步的(即如果没有可用的项目它会阻止).您需要的是某种异步集合,您可以使用ISourceBlock(特别是TransformBlock)来自TPL Dataflow:
ISourceBlock<TDst> Foo<TSrc, TDest>(IEnumerable<TSrc> source)
{
var block = new TransformBlock<TSrc, TDest>(
async s => await ExecuteOrDownloadSomethingAsync(s),
new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded
});
foreach (var item in source)
block.Post(item);
block.Complete();
return block;
}
Run Code Online (Sandbox Code Playgroud)
如果源是"慢"(即您希望Foo()在迭代source完成之前开始处理结果),您可能希望将调用foreach和Complete()调用分开Task.更好的解决方案就是制作source一个ISourceBlock<TSrc>.
| 归档时间: |
|
| 查看次数: |
4336 次 |
| 最近记录: |