【问题标题】:The 'await' operator can only be used within an async lambda expression error'await' 运算符只能在异步 lambda 表达式错误中使用
【发布时间】:2016-02-08 17:06:17
【问题描述】:

我有这个功能:

    public async Task<IEnumerable<RegionBreif>> GetAsync()
    {

    return await Table.Where(x => x.SiteId == _siteId).Select(r => new RegionBreif
    {
        IsServiceable = await RegionBreif.checkIfServicable(Context, r.SiteId, r.Id)
    }).ToArrayAsync();
}

还有这个功能:

public static async Task<bool?> checkIfServicable(DbContext context, int? _siteId, int _regionId)
{
    var t = (from ir in context.Set<InspectionReview>()
             join so in context.Set<SiteObject>() on ir.ObjectId equals so.Id
             where so.SiteRegionId == _regionId && so.SiteId == _siteId
             select (bool?)
             ir.IsNormal);

    return t.Count() == 0 ? (bool?)null : t.Any(x => x.Value == false) ? false : true;
}

在这一行:

await RegionBreif.checkIfServicable(Context, r.SiteId, r.Id)

我收到此错误:

错误 13 'await' 运算符只能在异步 lambda 表达式中使用。考虑用 'async' 修饰符标记这个 lambda 表达式。

【问题讨论】:

    标签: c# .net async-await


    【解决方案1】:

    问题在于您传递给Select 的lambda 表达式。如果你想在创建类型RegionBreif 中使用await,你必须传递一个async lambda 表达式,如下所示:

    Select(async r => new RegionBreif
    {
        IsServiceable = await RegionBreif.checkIfServicable(Context, r.SiteId, r.Id)
    })
    

    【讨论】:

    • 注意,这将使ToArrayAsync() 重新运行Task&lt;Task&lt;T&gt;[]&gt; 而不是Task&lt;T[]&gt;
    猜你喜欢
    • 2014-01-02
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2020-05-26
    相关资源
    最近更新 更多