Home > OS >  Parallel Read and Dbcontext threading ssues
Parallel Read and Dbcontext threading ssues

Time:03-22

We have to read 2 select statements need to run parallelly, means should be awaited together.

var t1 = GetSomeData1(somParams);
var tWrite = await WriteData(someParams);
var t2 = GetSomeData2(somParams);
await Task.WhenAll(t1, t2);

Note 1 write is between but in errors we see this error sometimes,

System.InvalidOperationException: A second operation was started on this context before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913. at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection() at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()

As per this. https://docs.microsoft.com/en-us/ef/ef6/saving/transactions default transaction isolation level is READ COMMITED.

I know read and write in READ COMMITED causes blocks but does we get the same error when we mix read and write.

What is the recommendation to avoid this error and use parallel reads.

CodePudding user response:

As it reads on the link from your exception:

Entity Framework Core does not support multiple parallel operations being run on the same DbContext instance. This includes both parallel execution of async queries and any explicit concurrent use from multiple threads. Therefore, always await async calls immediately, or use separate DbContext instances for operations that execute in parallel.

When EF Core detects an attempt to use a DbContext instance concurrently, you'll see an InvalidOperationException with a message like this:

A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext, however instance members are not guaranteed to be thread safe.

When concurrent access goes undetected, it can result in undefined behavior, application crashes and data corruption.

https://docs.microsoft.com/en-us/ef/core/dbcontext-configuration/#avoiding-dbcontext-threading-issues

  • Related