如何在 Linq 查询中等待方法 [英] How to await a method in a Linq query

查看:33
本文介绍了如何在 Linq 查询中等待方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在 LINQ 查询中使用 await 关键字,我得到了这个:

Trying to use the await keyword in a LINQ query and I get this:

'await' 操作符只能用在初始 'from' 子句的第一个集合表达式内或 'join' 子句的集合表达式内的查询表达式中

示例代码:

var data = (from id in ids
            let d = await LoadDataAsync(id)
            select d);

是否不可能在 LINQ 查询中等待某些内容,或者是否需要以不同的方式对其进行结构化?

Is it not possible to await something in a LINQ query, or does it need to be structured a different way?

推荐答案

LINQ 对 async/await 的支持非常有限.对于 LINQ 到对象,我所知道的唯一真正有用的操作是使用 async 委托执行 Select(这会产生一系列任务).>

LINQ has very limited support for async/await. For LINQ-to-objects, the only really useful operation I know of is to do a Select with an async delegate (which results in a sequence of tasks).

List<T> data = new List<T>();
foreach (var id in ids)
  data.Add(await LoadDataAsync(id));

如果您可以安全地并行执行 LoadDataAsync,您的示例可以重写为:

If you can do LoadDataAsync in parallel safely, your example could be rewritten as:

T[] data = await Task.WhenAll(ids.Select(id => LoadDataAsync(id)));

这篇关于如何在 Linq 查询中等待方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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