In EF Core, why does one DbContext shared by concurrent work fail under load, and what does EF throw when it detects the overlap?
answer
- one operation at a time
- change tracker is not synchronised
- InvalidOperationException: a second operation
- EnableThreadSafetyChecks defaults to true
- IDbContextFactory<T> per parallel branch
basics
~20 sA DbContext is not thread-safe: its change tracker, connection and transaction state assume one operation at a time. When a second operation starts before the first completes, EF throws InvalidOperationException; when the overlap goes undetected, results and tracked state can be corrupted.
solid answer
~40 sEF Core does not support parallel operations on one `DbContext` instance, whether from several threads or from async queries started without awaiting. The context's change tracker, open connection and current transaction are unsynchronised state. EF's concurrency detector, on by default via `EnableThreadSafetyChecks`, throws `InvalidOperationException`: "A second operation was started on this context instance before a previous operation completed." Detection is best-effort, so an undetected overlap can corrupt tracked data. Typical causes are a context held by a singleton or static field, or `Task.WhenAll` over queries on one context. Fixes: await each call before the next, or give every parallel branch its own context, for example from `IDbContextFactory<TContext>`.
code
csharp · 17 linespublic sealed class HomePageQuery(IDbContextFactory<NewsContext> factory)
{
public async Task<HomePage> LoadAsync(CancellationToken ct)
{
var top = LoadAsync(db => db.Articles.Where(a => a.IsTop), ct);
var breaking = LoadAsync(db => db.Articles.Where(a => a.IsBreaking), ct);
await Task.WhenAll(top, breaking);
return new HomePage(top.Result, breaking.Result);
}
private async Task<List<Article>> LoadAsync(
Func<NewsContext, IQueryable<Article>> query, CancellationToken ct)
{
await using var db = await factory.CreateDbContextAsync(ct);
return await query(db).AsNoTracking().ToListAsync(ct);
}
}go deeper
Recall that a DbContext is not thread-safe, that every async EF call should be awaited before the next, and the exception message about a second operation.
Explain which context state overlaps corrupt, why Task.WhenAll on one context fails, and how a factory gives each branch its own instance.
Diagnose shared contexts in production: singletons holding a context, fire-and-forget calls, background work using a request's context, and why detection is best-effort.
Decide where parallel data access is worth extra connections and contexts, and how to keep the rule enforceable across a large team.
## The rule EF Core's documentation is blunt: it **does not support multiple parallel operations on the same `DbContext` instance**. That covers both: - explicit use from several threads at once, and - several **async** operations started on one context without awaiting the first. A context is designed as a single-user session. Its internals are ordinary, unsynchronised objects. ## What is shared and why it breaks | Context state | What goes wrong when two operations overlap | |---|---| | The **change tracker** (identity map, entry states, snapshots) | Two queries materialise and fix up entities into the same dictionaries at once | | The **connection** | A provider connection generally runs one command at a time on one connection | | The **current transaction** | One branch commits or rolls back work the other thought it owned | | `SaveChanges` bookkeeping | Change detection runs while another branch is still modifying entries | Under light traffic the overlap is rare, so the bug survives testing and appears under load, when timing changes. ## What EF throws EF Core includes a **concurrency detector**. When it sees a second operation begin on an instance whose previous operation has not finished, it throws: - `InvalidOperationException`: "A second operation was started on this context instance before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext." Points to remember about the detector: 1. It is **on by default**: `DbContextOptionsBuilder.EnableThreadSafetyChecks(bool enableChecks = true)` lets you turn it off for a small performance gain, and EF warns that behaviour is then undefined if concurrency happens. 2. It is **best-effort**. The documentation says undetected concurrent access can lead to undefined behaviour, crashes and data corruption. 3. An `InvalidOperationException` from EF can leave the context in an **unrecoverable state**, so the instance should be discarded, not retried. ## How shared contexts happen - A **singleton** service, a static field or a cached object holding a context, so every request uses the same instance. - **Fire-and-forget async**: calling `ToListAsync()` without `await`, then issuing another query. - **`Task.WhenAll`** over several queries on one injected context, for instance a news home page that loads top stories, breaking news and most-read lists "in parallel". - **`Parallel.ForEach`** or background tasks spawned from a request that keep using the request's context. Note that `async` itself does not move work to another thread. The problem is two operations being in flight on one instance at the same time. ## Fixes 1. **Await immediately.** Run the queries one after another on one context. For most endpoints this is fast enough and the simplest choice. 2. **One context per parallel branch.** Take an `IDbContextFactory<TContext>` and create a context inside each branch with `CreateDbContextAsync()`, disposing it at the end. 3. **Do not let a context outlive its unit of work.** A singleton or background worker that needs data creates its own context per job from the factory. 4. **Keep the checks on.** Disable `EnableThreadSafetyChecks` only after measuring a real gain and testing thoroughly for concurrency bugs. ```csharp // broken: three queries in flight on one context var (top, breaking, popular) = ( db.Articles.Where(a => a.IsTop).ToListAsync(), db.Articles.Where(a => a.IsBreaking).ToListAsync(), db.Articles.OrderByDescending(a => a.Views).Take(10).ToListAsync()); await Task.WhenAll(top, breaking, popular); ``` ## Diagnosing it in production The failure rarely looks the same twice, which is why it is hard to pin down: - intermittent `InvalidOperationException` about a second operation, only under load; - provider errors raised below EF, such as Npgsql's `NpgsqlOperationInProgressException` ("A command is already in progress"), when two commands reach one connection; - entities from one request turning up in another, or `SaveChanges` writing changes nobody in the current request made, when a context is held by a singleton; - "Cannot access a disposed context instance" when background work keeps using a request's context after the request ended. The first diagnostic step is to find **who owns the instance**: trace where the context is resolved and check whether any service with a longer lifetime holds it. ## Why a separate context is cheap Creating a context does not open a connection or rebuild the model; the model is cached per context type and connections come from the driver's pool. A context per branch costs some allocations, which pooling can reduce further, and each branch then uses its own connection.
- Is it ever safe to turn off EnableThreadSafetyChecks?Only when profiling shows the detector costs something measurable and the code has been tested thoroughly against concurrent use. Turning it off removes the informative `InvalidOperationException`, not the problem: concurrent use then has undefined behaviour and can fail in unpredictable ways.
- Why is a per-request context safe in an ordinary ASP.NET Core endpoint?Each request gets its own dependency-injection scope and therefore its own context instance, and a request's code normally runs one awaited operation at a time. The danger returns only when that request starts parallel work on its context or hands the context to code that outlives the request.
- DbContext is thread-safe as long as every query is async.
- Task.WhenAll over queries on one context is a safe way to speed up a page.
- EF serialises overlapping operations on one context with an internal lock.
- If EF does not throw, concurrent use of one context is fine.
- Disabling EnableThreadSafetyChecks makes concurrent use of one context supported.