实体框架是否支持并行异步查询? [英] Does Entity Framework support parallel async queries?

查看:217
本文介绍了实体框架是否支持并行异步查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们启动多个异步实体框架查询并且并行运行它们时会发生什么?

What happens when we start multiple async Entity Framework queries and run them in parallel?

它们是否并行执行?实体框架是否被序列化?这不受支持吗?是否导致异常?

Are they physically executed in parallel? Are they serialized by Entity Framework? Is this unsupported? Does it result in an exception?

public async Task QueryDatabase()
{
    using (var context = new MyDbContext())
    {
        Task task1 = context.SomeTable1.ToListAsync();
        Task task2 = context.SomeTable2.ToListAsync();

        await Task.WhenAll(task1, task2);
    }
}


推荐答案

不支持按照规格版本6

这应该抛出一个 DbConcurrencyException 异常说


在前一个
异步操作完成之前,第二个操作是在此上下文中开始的。
使用'await'确保任何$ b $在此上下文调用另一个方法
之前,b异步操作已经完成。任何实例成员不能保证是线程
安全。

A second operation started on this context before a previous asynchronous operation completed. Use 'await' to ensure that any asynchronous operations have completed before calling another method on this context. Any instance members are not guaranteed to be thread safe.

如果开发人员尝试执行两个异步操作,EF将检测一次并抛出

EF will detect if the developer attempts to execute two async operations at one time and throw.

项目的代码页面


启用数据库操作的异步执行实际上是
与在同一上下文中启用并发执行正交。在
中,服务器方案的具体情况,使用并发访问可能会导致
负面影响可伸缩性,因为这意味着为了
处理单个请求,您将会旋转任意数
不同的线程。所有的线程将争取资源,例如
作为内存与服务器其他并发
请求所需的其他线程。

Enabling asynchronous execution of database operations is actually orthogonal to enabling concurrent execution on the same context. In the particular case of server scenarios, using concurrent access could affect scalability negatively as it would mean that in order to process a single request you would be spinning of an arbitrary number of different threads. All the threads would compete for resources such as memory with other threads necessary to server other concurrent requests.

这篇关于实体框架是否支持并行异步查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆