本文介绍了何时使用OrderByCompletion(乔恩斯基特)VS Parallel.ForEach与异步委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

近日乔恩斯基特在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 execute async code. Parallel.ForEach doesn't understand async, so your lambda will be turned into async 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 (not Tasks), you want to perform some async action for each of them and the actions should execute in parallel.

  • Use OrderByCompletion() when you have a collection of Tasks, you want perform some action (asynchronous or not) for the result of each Task, the actions should not execute in parallel and you want to execute the actions based on the order in which the Tasks complete.

这篇关于何时使用OrderByCompletion(乔恩斯基特)VS Parallel.ForEach与异步委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 19:03