首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >异步/等待多个CountAsync数据库调用EFCore

异步/等待多个CountAsync数据库调用EFCore
EN

Stack Overflow用户
提问于 2019-07-27 01:02:53
回答 1查看 2.9K关注 0票数 0

我正在尝试确保我理解async/await。在下面的示例中,我的代码是异步运行还是同步运行?

我的理解可能是错误的,即每次异步数据库调用都不必等待前一次调用完成。因此,我基本上可以运行多个CountAsync调用,它们都会同时运行,直到此时有人试图从其中一个异步调用中获取数据。

这是我目前所拥有的:(所有的select/where逻辑都被删除了,因为这个问题不需要它)

代码语言:javascript
复制
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;
    }

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

EN

回答 1

Stack Overflow用户

发布于 2019-07-27 01:21:32

任务返回热,或已启动。await关键字的字面意思是在此停止,直到任务完成。因此,是的,使用您拥有的代码,每个查询都将按顺序连续运行,一次一个,因为您继续操作,然后在每一行停止。

要并行运行,只需启动任务即可。例如:

代码语言:javascript
复制
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。然后,在您启动所有任务之后:

代码语言:javascript
复制
model.TotalCustomers = await totalCustomersTask;

model.MyTotalCustomers = await myTotalCustomersTask;
model.MyClosedCustomers = await myClosedCustomersTask;
model.MyNotStartedCustomers = await myNotStartedCustomers;

...

异步与“并行”不是一回事,尽管异步操作可以并行运行。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57224349

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档