我如何使用异步用foreach? [英] How can I use Async with ForEach?

查看:122
本文介绍了我如何使用异步用foreach?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能使用的ForEach时使用异步?下面是code我想:

Is it possible to use Async when using ForEach? Below is the code I am trying:

using (DataContext db = new DataLayer.DataContext())
{
    db.Groups.ToList().ForEach(i => async {
        await GetAdminsFromGroup(i.Gid);
    });
}

我收到错误:

异步这个名字并不在当前的背景下存在

The name 'Async' does not exist in the current context

using语句被封闭的方法设置为异步。

The method the using statement is enclosed in is set to async.

推荐答案

列表< T> .ForEach 异步发挥特别好(均未做LINQ到对象,出于同样的原因)。

List<T>.ForEach doesn't play particularly well with async (neither does LINQ-to-objects, for the same reasons).

在这种情况下,我推荐的突出的每个元素到异步操作时,你就可以(异步)等待它们全部完成。

In this case, I recommend projecting each element into an asynchronous operation, and you can then (asynchronously) wait for them all to complete.

using (DataContext db = new DataLayer.DataContext())
{
    var tasks = db.Groups.ToList().Select(i => GetAdminsFromGroupAsync(i.Gid));
    var results = await Task.WhenAll(tasks);
}

这种方法超过给人一种异步授人以的ForEach 的好处是:


  1. 错误处理是更恰当。从异步无效例外无法与被抓;这种方法将传播在等待Task.WhenAll 线异常,让自然异常处理。

  2. 您知道任务完成这个方法结束,因为它的等待Task.WhenAll 。如果你使用异步无效,你不能轻易当操作完成诉说。

  3. 此方法具有检索结果的自然的语法。 GetAdminsFromGroupAsync 听起来就像是产生一个结果(管理员)的操作,这样的code是更自然,如果这种行动能的收益的其结果,而不是设置一个值作为一个副作用。

  1. Error handling is more proper. Exceptions from async void cannot be caught with catch; this approach will propagate exceptions at the await Task.WhenAll line, allowing natural exception handling.
  2. You know that the tasks are complete at the end of this method, since it does an await Task.WhenAll. If you use async void, you cannot easily tell when the operations have completed.
  3. This approach has a natural syntax for retrieving the results. GetAdminsFromGroupAsync sounds like it's an operation that produces a result (the admins), and such code is more natural if such operations can return their results rather than setting a value as a side effect.

这篇关于我如何使用异步用foreach?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆