c# - 异步/等待多个 Linq 语句
问题描述
我有一个 API 控制器操作,它执行大约 10 个单独的 linq 查询,这些查询用于形成我需要发送回客户端的摘要对象。这些 linq 查询都是在相同的数据上执行的。有没有一种方法可以在这种情况下使用 async/await 以便一个 linq 语句不必阻止其他语句运行?如果是这样,编写该异步/等待代码的最有效方法是什么?
总结一下我的问题:
- 在这种情况下,我有异步/等待的用例吗?
- 如果是这样,与其创建一堆独立的任务,然后将它们全部填充到 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 和最便宜的产品在不等待完成的情况下执行?
解决方案
由于您正在工作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()
.
推荐阅读
- python - Python 和 tkinter:我如何允许 python 中的函数创建一个 sqlite3 数据库
- excel - VBA Copying a Pasting to Sharepoint
- cordova - Ionic Android - 你如何重命名构建的输出文件?
- git - 在进行 git rebase 时,为什么 git 需要一个完全干净的工作目录,包括不受 rebase 影响的文件?
- html - thymeleaf 在源代码中呈现附加标签
- visual-studio - 使用 Visual Studio Web 项目进行变更集管理
- python-3.x - 接收文件名中带有时间戳的文件的适当方法是什么?
- mysql - 错误 ModuleNotFoundError:没有名为“pymysql”的模块
- android - 使用动态数据解析非常大的 JSON 文件
- python - 根据字典值打印单数/复数