
One DbContext, Many Tasks: Why Parallel Queries on a Context Fail
- كاتب موثّق
- EF Core 10
محتويات المقال
Task.WhenAll. The integration tests run on SQLite and pass. On staging, against SQL Server, nearly every call fails with InvalidOperationException: A second operation was started on this context instance before a previous operation completed. Someone adds MultipleActiveResultSets=True to the connection string. Nothing changes.
The common misconception
Task.WhenAll runs them side by side and the endpoint waits only as long as the slowest one. They're reads, so running them on the same context can't hurt anything.
HttpClient is designed for concurrent calls, and firing several requests and awaiting them together is a textbook way to cut latency. ToListAsync returns a Task like any other, nothing in its signature says "one at a time", and a query looks read-only. The code even passes its tests, and MARS sounds like the setting that allows several queries on one connection.
What actually happens
A context is one conversation with the database
DbContext holds a single connection, a single and the state of the operation in progress. Even a read changes it: a tracking query adds every entity it returns to the change tracker. Microsoft's docs are direct: DbContext isn't thread-safe, and EF Core doesn't support multiple parallel operations on the same instance, including parallel execution of async queries. The rule is to await each async call before using the context again.
Task.WhenAll starts everything before it awaits anything
CountAsync() starts the query and hands back a Task as soon as the command is waiting on the network. The next line then starts a second query on the same context while the first is still in flight. EF Core's thread-safety check sees an operation already running and throws. In a test with EF Core 10 on SQL Server LocalDB, the three-query Task.WhenAll failed in 199 of 200 runs. The one pass is what makes the bug slippery: it's a race, and a fast query sometimes finishes before the next one starts.
await creates the same overlap. Storing SaveChangesAsync() in a variable and querying before awaiting it failed in 198 of 200 runs.
Why the SQLite tests passed
Task, and nothing ever overlaps. In the test, the same Task.WhenAll passed 100 of 100 runs on SQLite. With an interceptor that adds 20 ms of delay to every command, standing in for a network hop, it failed every run. A test database that never yields will never show you this bug.
MARS and switching off the check don't fix it
EnableThreadSafetyChecks(false) removes the check, and the performance guide offers it only to apps that have been thoroughly tested to be free of this bug. Switched off, the driver failed instead: "The connection does not support MultipleActiveResultSets" in 199 of 200 runs. With MARS on as well, 199 runs appeared to work, and one failed with "BeginExecuteReader requires an open and available Connection. The connection's current state is closed": the query that finished first had closed the connection the others were still using. That's the undefined behavior the docs warn about, now rare enough to slip past review.
The check doesn't cover everything
Parallel.For adding 5,000 products to a context that had already run a query broke all 20 runs, with IndexOutOfRangeException or "Operations that change non-concurrent collections must have exclusive access" thrown from inside the change tracker. There was no friendly EF Core message pointing at the cause.
The fix: one context per concurrent operation
using Microsoft.EntityFrameworkCore;public sealed class DashboardQuery(ShopDb db){ public async Task<Dashboard> LoadAsync(CancellationToken ct) { // All three start on the same context before any of them finishes var count = db.Orders.CountAsync(ct); var revenue = db.Orders.SumAsync(o => o.Total, ct); var top = db.Products.OrderByDescending(p => p.Sold) .Take(5).ToListAsync(ct); // Throws: a second operation was started on this context await Task.WhenAll(count, revenue, top); return new Dashboard(await count, await revenue, await top); }}using Microsoft.EntityFrameworkCore;// Program.cs: builder.Services.AddDbContextFactory<ShopDb>(...)public sealed class DashboardQuery(IDbContextFactory<ShopDb> factory){ public async Task<Dashboard> LoadAsync(CancellationToken ct) { var count = RunAsync(db => db.Orders.CountAsync(ct), ct); var revenue = RunAsync(db => db.Orders.SumAsync(o => o.Total, ct), ct); var top = RunAsync(db => db.Products.OrderByDescending(p => p.Sold) .Take(5).ToListAsync(ct), ct); await Task.WhenAll(count, revenue, top); return new Dashboard(await count, await revenue, await top); } private async Task<T> RunAsync<T>( Func<ShopDb, Task<T>> query, CancellationToken ct) { // Each query gets its own context, and its own connection await using var db = await factory.CreateDbContextAsync(ct); return await query(db); }}AddDbContextFactory registers an as a singleton and also registers the context itself as scoped, so the rest of the app can keep injecting ShopDb. Contexts created by the factory aren't managed by the container, which is why RunAsync disposes each one. In the test, this version returned the right numbers on every run.
await in front of each call on one context is correct and usually fast enough: async already frees the thread while each query waits. Parallel contexts pay off only when queries are slow and truly independent, and they cost something. Each one borrows its own pooled connection, so one request holds three at once, and the queries share no transaction, so they can see the database at slightly different moments.
await each query on one context | ||
Task.WhenAll on one context | ||
Task.WhenAll, one context per task | ||
Parallel.ForEach over a shared context |
How to apply it in your project
Search for the overlapping shapes Look for Task.WhenAll,Parallel.ForEach,Select(async ...)and async calls stored in a variable instead of awaited, anywhere they touch the same context.Await by default On a request's own context, await every EF Core call before the next one. That's correct, simple and rarely the bottleneck. Give parallel work its own contexts Where parallelism is measured to help, register AddDbContextFactory, create one context per task withCreateDbContextAsync, dispose it, and don't pass tracked entities between tasks.Watch the long-lived scopes In Blazor Server a scoped context lives for the whole circuit, so the docs recommend the factory there. Background loops and hosted services should create a context or a scope per unit of work too.
Key takeaways
A DbContextruns one operation at a time;Task.WhenAllon one context throws "A second operation was started on this context instance".SQLite runs async methods synchronously, so tests on it hide the overlap that a networked database exposes. MARS doesn't help, and EnableThreadSafetyChecks(false)only hides the error behind driver failures and corrupted state.Await each call by default; when queries are slow and independent, give each one its own context from IDbContextFactory.Parallel contexts cost a connection each and share no transaction, so use them where you've measured a gain.
التعليقات (0)