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

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

问题描述

当我们启动多个异步实体框架查询,会出现什么情况和并行运行呢?

他们是否身在并行执行?他们是否通过序列化实体框架?这是不支持的?这是否导致异常?

 公共异步任务QueryDatabase()
{
    使用(VAR上下文=新MyDbContext())
    {
        任务任务1 = context.SomeTable1.ToListAsync();
        任务TASK2 = context.SomeTable2.ToListAsync();

        等待Task.WhenAll(任务1,TASK2);
    }
}
 

解决方案

这是不支持按的<一个href="https://entityframework.$c$cplex.com/wikipage?title=Task-based%20Asynchronous%20Pattern%20support%20in%20EF.#ThreadSafety">specifications版本6 。

这应该抛出一个 DbConcurrencyException 除了说

  

第二次手术开始在此背景下之前,previous   异步操作完成。使用等待,以确保任何   异步操作调用另一个方法之前完成   关于这方面。所有实例成员都不能保证是线程   安全的。

     

EF将检测如果开发商试图执行两个异步操作在同一时间,并抛出

项目的codePLEX页:

  

数据库操作的启用异步执行实际上是   正交使并发执行在同样的背景下。在   的服务器方案的特定情况下,使用并发访问可能   负面影响的可扩展性,因为这将意味着,为了   处理您将纺丝的任意数量的单个请求   不同的线程。所有的线程会争夺资源,   内存与必要的服务器等并发其他线程   请求。

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);
    }
}

解决方案

This is not supported as per the specifications of version 6.

This should throw a DbConcurrencyException exception saying

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 will detect if the developer attempts to execute two async operations at one time and throw.

From a codeplex page of the project:

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天全站免登陆