c# - 异步/等待多个 CountAsync 数据库调用 EFCore
问题描述
我试图确保我理解 async/await。在以下示例中,我的代码是异步运行还是同步运行?
我的理解(可能是错误的)是每个异步数据库调用都不必等待上一个调用完成。因此,我基本上可以运行多个CountAsync
调用,并且它们都将同时运行,直到此时某些东西试图从其中一个异步调用中获取数据。
这是我目前拥有的:(所有选择/位置逻辑已被删除,因为这个问题不需要它)
public async Task<DashboardModel> GetDashboard(DashboardInput input)
{
DashboardModel model = new DashboardModel();
model.MyCustomers = await _context.Customers.Where(x => [...]).Select(x => new DashboardCustomerModel()
{
[...]
}).ToListAsync();
model.TotalCustomers = await _context.Customers.CountAsync(x => [...]);
model.MyTotalCustomers = await _context.Customers.CountAsync(x => [...]);
model.MyClosedCustomers = await _context.Customers.CountAsync(x => [...]);
model.MyNotStartedCustomers = await _context.Customers.CountAsync(x => [...]);
model.OtherTotalCustomers = await _context.Customers.CountAsync(x => [...]);
model.OtherClosedCustomers = await _context.Customers.CountAsync(x => [...]);
model.OtherNotStartedCustomers = await _context.Customers.CountAsync(x => [...]);
model.PreparerApprovedCustomers = await _context.Customers.CountAsync(x => [...]);
model.ReviewerApprovedCustomers = await _context.Customers.CountAsync(x => [...]);
model.ApprovedCustomers = await _context.Customers.CountAsync(x => [...]);
return model;
}
我的同事说这是不正确的,所有的调用都会同步运行;因此我问这个问题的原因。如果我错了,那么编写此方法以使所有异步调用同时运行的正确方法是什么?
解决方案
任务返回热,或已经开始。关键字的await
字面意思是在任务完成之前停止。所以,是的,使用您拥有的代码,每个查询将按顺序依次运行,一次一个,当您继续然后在每一行停止时。
要并行运行,您只需启动任务。例如:
var totalCustomersTask = _context.Customers.CountAsync(x => [...]);
var myTotalCustomersTask = _context.Customers.CountAsync(x => [...]);
var myClosedCustomers = _context.Customers.CountAsync(x => [...]);
var myNotStartedCustomers = _context.Customers.CountAsync(x => [...]);
...
请注意,await
这些行中的任何一行都没有。然后,在您启动所有任务之后:
model.TotalCustomers = await totalCustomersTask;
model.MyTotalCustomers = await myTotalCustomersTask;
model.MyClosedCustomers = await myClosedCustomersTask;
model.MyNotStartedCustomers = await myNotStartedCustomers;
...
异步与“并行”不同,尽管异步操作可以并行运行。
推荐阅读
- javascript - 将焦点放在输入上并更改 li 背景颜色
- c++ - 关于两个类构造函数的C++问题
- javascript - TS2339:“元素”类型上不存在属性“样式”?
- java - 如何避免在 IDEA 中强制转换类型?
- android-studio - 我可以通过互联网更新我的 Mutablelist 吗?
- kubernetes - 如何删除 Kubernetes 命名空间上的标签
- javascript - 从 ReactJS 中的图像中提取链接文本坐标
- sql-server - 使用 GROUP BY 子句时的 T-SQL Lead () 函数问题
- python - 如何在 PyICU 中进行“自然排序”?
- xamarin - Application.Current.MainPage 在 OnAppearing 内工作,但不在按钮单击上