首页 > 解决方案 > 异步/等待多个 Linq 语句

问题描述

我有一个 API 控制器操作,它执行大约 10 个单独的 linq 查询,这些查询用于形成我需要发送回客户端的摘要对象。这些 linq 查询都是在相同的数据上执行的。有没有一种方法可以在这种情况下使用 async/await 以便一个 linq 语句不必阻止其他语句运行?如果是这样,编写该异步/等待代码的最有效方法是什么?

总结一下我的问题:

  1. 在这种情况下,我有异步/等待的用例吗?
  2. 如果是这样,与其创建一堆独立的任务,然后将它们全部填充到 Task.WhenAll() 中,是否有更有效的方法来编写它,以便我以后可以轻松地添加更多 linq 查询?(没什么太疯狂的,只是干净且可维护)。
[HttpGet]
public IActionResult GetInventoryDetails(string id)
{
    var inventory = _storeInventoryRepo.FindByCondition(s => s.Id = id)

    var uniqueProductCount = inventory.Select(x => x.ProductId).Distinct().ToList().Count

    var totalProductInventoryValue = inventory.Sum(x =>x.UnitPrice & x.TotalUnits)

    var cheapestProduct = inventory.OrderBy(x => x.unitPrice).Select(x => x.ProductId).First();

    var inventorydetails = new InventoryDetails
    {
       UniqueProductCount = uniqueProductCount,
       TotalProductInventoryValue = totalProductInventoryValue,
       CheapestProduct = cheapestProduct
    }

    Return Ok(inventoryDetails)
}

    public class ProductInventory
    {
        public string Id { get; set; }
        public string ProductId { get; set; }
        public int UnitPrice { get; set; }
        public double TotalUnits { get; set; }
    }

我将如何使用 async/await 来允许 uniqueProductCost、totalProductInventoryValue 和最便宜的产品在不等待完成的情况下执行?

标签: c#.netasp.net-coreasync-await

解决方案


由于您正在工作IEnumerable<T>而不是IQueriable<T>,因此您不能使用async-await.

除非你使用Task.Run. 但是就像async-await在 ASP.NET 中使用真正的异步 API(如 I/O)一样,您会牺牲性能来换取可用性,使用Task.Run也会牺牲可用性来换取性能。

如果你使用Select(x => x.ProductId).Distinct(). Count(),与使用Select(x => x.ProductId).Distinct().ToList().Count.

使用inventory.OrderBy(x => x.unitPrice).First().ProductId而不是inventory.OrderBy(x => x.unitPrice).Select(x => x.ProductId).First().


推荐阅读