我正在尝试确保我理解async/await。在下面的示例中,我的代码是异步运行还是同步运行?
我的理解可能是错误的,即每次异步数据库调用都不必等待前一次调用完成。因此,我基本上可以运行多个CountAsync调用,它们都会同时运行,直到此时有人试图从其中一个异步调用中获取数据。
这是我目前所拥有的:(所有的select/where逻辑都被删除了,因为这个问题不需要它)
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;
}我的同事说这是不正确的,所有的调用都将同步运行;因此我问这个问题的原因。如果我错了,那么什么是正确的方法来编写此方法,以便所有异步调用同时运行?
发布于 2019-07-27 01:21:32
任务返回热,或已启动。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;
...异步与“并行”不是一回事,尽管异步操作可以并行运行。
https://stackoverflow.com/questions/57224349
复制相似问题