Does Entity Framework support parallel async queries?
.NetEntity FrameworkEntity Framework-6.Net Problem Overview
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);
}
}
.Net Solutions
Solution 1 - .Net
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.
Solution 2 - .Net
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.
Solution 3 - .Net
Just wanted to update that with EF 5 it's now possible to split queries that load navigation properties in separate queries: https://docs.microsoft.com/en-us/ef/core/querying/single-split-queries
Still not solving your case but might be useful to know.