并行读取和 Dbcontext 线程问题

Parallel Read and Dbcontext threading ssues

我们必须阅读 2 select 个语句需要 运行 并行,意味着应该一起等待。

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

注意 1 写入介于两者之间,但在错误中我们有时会看到此错误,

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()

据此。 https://docs.microsoft.com/en-us/ef/ef6/saving/transactions 默认事务隔离级别是 READ COMMITED。

我知道在 READ COMMITED 中读取和写入会导致块,但是当我们混合读取和写入时是否会遇到相同的错误。

避免此错误并使用并行读取的建议是什么。

正如它在 link 上从您的异常中读取的那样:

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