何时使用OrderByCompletion(乔恩斯基特)VS Parallel.ForEach与异步委托 [英] When to use OrderByCompletion (Jon Skeet) vs Parallel.ForEach with async delegates
问题描述
近日乔恩斯基特在NDC伦敦谈到了C#5异步/等待和presented 按完成订购的一的异步任务列表的想法。链接<一个href=\"http://msmvps.com/blogs/jon_skeet/archive/2012/01/16/eduasync-part-19-ordering-by-completion-ahead-of-time.aspx\" rel=\"nofollow\">http://msmvps.com/blogs/jon_skeet/archive/2012/01/16/eduasync-part-19-ordering-by-completion-ahead-of-time.aspx
我有点困惑或者我应该说我不知道什么时候这个技术更适合使用。
我不明白这一点,下面的例子之间的差异
VAR包=新ConcurrentBag&LT;对象&gt;();
Parallel.ForEach(MyCollection的,异步项=&GT;
{
//一些pre的东西
VAR响应=等待的GetData(项目);
bag.Add(响应);
//一些东西后
}
或的 ForEachAsync 的:由斯蒂芬Toub解释 - 的 http://blogs.msdn.com/b/pfxteam/archive/2012/03/05/10278165.aspx
编辑:发现了的博客文章从斯蒂芬Toub 解释&LT; =>处理任务,他们完成。值得一读。在阅读完之后,我可以清楚地了解它是如何工作的原因,还当使用这种技术。
块引用>解决方案
不要使用
Parallel.ForEach
执行异步
code。Parallel.ForEach
不明白异步
,所以你的拉姆达将变成异步无效
,这将无法正常工作(Parallel.ForEach
将所有的工作完成之前返回;异常将无法得到妥善处理;其他可能的问题)。使用类似
ForEachAsync()
当你有对象的集合(不是工作
S) ,要执行的为他们每个人的某些异步
动作和行动应并行执行。使用
OrderByCompletion()
当你有工作
S,你要执行一些动作的集合(异步与否)为每个结果工作
,动作应的不的并行执行,并且希望基于顺序执行的行动其中,工作
必须填写。Recently Jon Skeet at NDC London spoke about C# 5 async/await and presented the idea of "ordering by completion" a list of async tasks. A link http://msmvps.com/blogs/jon_skeet/archive/2012/01/16/eduasync-part-19-ordering-by-completion-ahead-of-time.aspx
I am a bit confused or should I say I am not sure when will this technique be more appropriate to use.
I cannot understand the difference between this and the below example
var bag = new ConcurrentBag<object>(); Parallel.ForEach(myCollection, async item => { // some pre stuff var response = await GetData(item); bag.Add(response); // some post stuff }
or ForEachAsync as explained by Stephen Toub - http://blogs.msdn.com/b/pfxteam/archive/2012/03/05/10278165.aspx
EDIT: Found a blog post from Stephen Toub explaining "Ordering by completion" <=> "Processing tasks as they complete". Worth reading. After reading this I could clearly understand the reasons how it works and also when to use this technique.
解决方案
Don't use
Parallel.ForEach
to executeasync
code.Parallel.ForEach
doesn't understandasync
, so your lambda will be turned intoasync void
, which won't work correctly (Parallel.ForEach
will return before all work is done; exceptions won't be handled properly; possibly other issues).Use something like
ForEachAsync()
when you have a collection of objects (notTask
s), you want to perform someasync
action for each of them and the actions should execute in parallel.Use
OrderByCompletion()
when you have a collection ofTask
s, you want perform some action (asynchronous or not) for the result of eachTask
, the actions should not execute in parallel and you want to execute the actions based on the order in which theTask
s complete.这篇关于何时使用OrderByCompletion(乔恩斯基特)VS Parallel.ForEach与异步委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!