Does Entity Framework support parallel async queries?

.net entity-framework entity-framework-6


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);
7/11/2014 4:15:11 PM

Accepted Answer

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.

Entity Framework Core does not support this scenario either.

EF Core doesn't support multiple parallel operations being run on the same context instance. You should always wait for an operation to complete before beginning the next operation. This is typically done by using the await keyword on each async operation.

2/10/2020 6:16:03 AM

Popular Answer

Just a note, as mentioned by ken2k this is not allowed when using Entity Framework with MS SQL Server. However, if you are using Entity Framework with Oracle, this is allowed.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow