الانتقال إلى المحتوى
.NETEF Core· 7 دقائق للقراءة

One DbContext, Many Tasks: Why Parallel Queries on a Context Fail

A DbContext runs one operation at a time. Task.WhenAll on a single context throws, and switching the check off trades the exception for broken state.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • EF Core 10
محتويات المقال

A dashboard endpoint runs three queries one after another: the order count, total revenue and the five best-selling products. To cut its latency, a developer starts all three and awaits them together with 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

The belief: async queries are independent operations, so 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.

It works almost everywhere else. 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

A 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

Calling 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.

Forgetting an 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

SQLite doesn't support asynchronous I/O, so Microsoft.Data.Sqlite runs its async methods synchronously. Each "async" query has already finished by the time it returns its 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

Multiple Active Result Sets () is a SQL Server connection setting that lets one connection carry several batches, and Microsoft's own docs say it doesn't imply operations run simultaneously. EF Core's check sits above the connection, so with MARS on, all 200 runs still failed with the same message.

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

The docs say the check catches this bug in many cases, not all. In a test, 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

C# DashboardQuery.cs
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);    }}

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.

Before reaching for it, ask whether you need parallelism at all. Putting 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.

OptionSafe?What it costs
await each query on one contextYesThe query times add up; one connection at a time
Task.WhenAll on one contextNo: throws, or breaks state with the check offNothing you'd want to keep
Task.WhenAll, one context per taskYesOne connection per query; no shared transaction or tracked entities
One query that returns every numberYesOne round trip, if EF Core can translate it
Parallel.ForEach over a shared contextNo: the change tracker isn't thread-safeRandom internal exceptions

How to apply it in your project

  1. Search for the overlapping shapesLook for Task.WhenAll, Parallel.ForEach, Select(async ...) and async calls stored in a variable instead of awaited, anywhere they touch the same context.
  2. Await by defaultOn a request's own context, await every EF Core call before the next one. That's correct, simple and rarely the bottleneck.
  3. Give parallel work its own contextsWhere parallelism is measured to help, register AddDbContextFactory, create one context per task with CreateDbContextAsync, dispose it, and don't pass tracked entities between tasks.
  4. Watch the long-lived scopesIn 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 DbContext runs one operation at a time; Task.WhenAll on 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.

📚 المصادر

  1. DbContext Lifetime, Configuration, and Initialization — EF Core, Microsoft Learn
  2. Asynchronous Programming — EF Core, Microsoft Learn
  3. Advanced Performance Topics — EF Core, Microsoft Learn
  4. Async limitations — Microsoft.Data.Sqlite, Microsoft Learn

التعليقات (0)