如何将 Async 与 ForEach 结合使用? [英] How can I use Async with 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>.ForEach
与 async
配合得不是特别好(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:
- 错误处理更恰当.
async void
的异常不能被catch
捕获;这种方法将在await Task.WhenAll
行传播异常,从而允许自然的异常处理. - 您知道任务在此方法结束时完成,因为它执行
await Task.WhenAll
.如果使用async void
,则无法轻易判断操作何时完成. - 这种方法具有用于检索结果的自然语法.
GetAdminsFromGroupAsync
听起来像是一个产生结果的操作(管理员),如果这样的操作可以返回他们的结果而不是设置一个值作为一边,这样的代码更自然 效果.
- Error handling is more proper. Exceptions from
async void
cannot be caught withcatch
; this approach will propagate exceptions at theawait Task.WhenAll
line, allowing natural exception handling. - You know that the tasks are complete at the end of this method, since it does an
await Task.WhenAll
. If you useasync void
, you cannot easily tell when the operations have completed. - 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屋!