首页 > 解决方案 > 异步/等待多个 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;
    }

我的同事说这是不正确的,所有的调用都会同步运行;因此我问这个问题的原因。如果我错了,那么编写此方法以使所有异步调用同时运行的正确方法是什么?

标签: c#asp.net-coreasync-awaitentity-framework-coreentity-framework-core-2.2

解决方案


任务返回热,或已经开始。关键字的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;

...

异步与“并行”不同,尽管异步操作可以并行运行。


推荐阅读