EF 6 - How to correctly execute concurrent queries

When creating a report, I have to fulfill 3 queries that are related to individual objects of the same context. Since they are quite heavy, I decided to use .ToListAsync(); so that they run in parallel, but, to my surprise, I get an exception to this ...

What is the correct way to execute queries in parallel using EF 6? Do I have to manually start new tasks?

Change 1
Code is basically

 using(var MyCtx = new MyCtx()) { var r1 = MyCtx.E1.Where(bla bla bla).ToListAsync(); var r2 = MyCtx.E2.Where(ble ble ble).ToListAsync(); var r3 = MyCtx.E3.Where(ble ble ble).ToListAsync(); Task.WhenAll(r1,r2,r3); DoSomething(r1.Result, r2.Result, r3.Result); } 
+11
source share
2 answers

The problem is this:

EF does not support processing multiple requests through the same DbContext object. If your second asynchronous request to the same DbContext instance is started before the first request completes (and this is the point), you will receive an error message that your request is processing regarding the open DataReader.

Source: https://visualstudiomagazine.com/articles/2014/04/01/async-processing.aspx

You will need to change the code like this:

 async Task<List<E1Entity>> GetE1Data() { using(var MyCtx = new MyCtx()) { return await MyCtx.E1.Where(bla bla bla).ToListAsync(); } } async Task<List<E2Entity>> GetE2Data() { using(var MyCtx = new MyCtx()) { return await MyCtx.E2.Where(bla bla bla).ToListAsync(); } } async Task DoSomething() { var t1 = GetE1Data(); var t2 = GetE2Data(); await Task.WhenAll(t1,t2); DoSomething(t1.Result, t2.Result); } 
+14
source

Check out https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/enabling-multiple-active-result-sets

From the documentation:

Alternating between SELECT and BULK INSERT statements is allowed. However, data manipulation language (DML) and data definition language operators (DDL) are performed atomically.

Then the above code will work, and you will get a performance gain when reading data.

0
source

Source: https://habr.com/ru/post/1263073/


All Articles