问题描述
近日乔恩斯基特在NDC伦敦谈到了C#5异步/等待和presented 按完成订购的一的异步任务列表的想法。链接http://msmvps.com/blogs/jon_skeet/archive/2012/01/16/eduasync-part-19-ordering-by-completion-ahead-of-time.aspx
我有点困惑或者我应该说我不知道什么时候这个技术更适合使用。
我不明白这一点,下面的例子之间的差异
VAR包=新ConcurrentBag<对象>();
Parallel.ForEach(MyCollection的,异步项=>
{
//一些pre的东西
VAR响应=等待的GetData(项目);
bag.Add(响应);
//一些东西后
}
或的 ForEachAsync 的:由斯蒂芬Toub解释 - 的
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与异步委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!