如何将 Async 与 ForEach 结合使用? [英] How can I use Async with ForEach?

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

问题描述

使用 ForEach 时是否可以使用 Async?以下是我正在尝试的代码:

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);
    });
}

我收到错误:

名称Async"在当前上下文中不存在

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

using 语句所包含的方法设置为 async.

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

推荐答案

List<T>.ForEachasync 配合得不是特别好(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);
}

这种方法相对于将 async 委托给 ForEach 的好处是:

The benefits of this approach over giving an async delegate to ForEach are:

  1. 错误处理更恰当.async void 的异常不能被 catch 捕获;这种方法将在 await Task.WhenAll 行传播异常,从而允许自然的异常处理.
  2. 您知道任务在此方法结束时完成,因为它执行 await Task.WhenAll.如果使用 async void,则无法轻易判断操作何时完成.
  3. 这种方法具有用于检索结果的自然语法.GetAdminsFromGroupAsync 听起来像是一个产生结果的操作(管理员),如果这样的操作可以返回他们的结果而不是设置一个值作为一边,这样的代码更自然
  4. 效果.
  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.

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

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