📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Why does EF Core throw 'A second operation was started on this context instance', and what are the correct ways to run database work in parallel?

Mid-Level Debugging Intermediate concurrency dbcontext dependency-injection ef-core parallelism

🎯 Key points

  • One connection, one change tracker, one operation at a time
  • Concurrency detector throws InvalidOperationException instead of corrupting state
  • Causes: shared context across threads, missing await, Task.WhenAll on one context, fire-and-forget after the request
  • Parallel work: one context per branch via IDbContextFactory<T>.CreateDbContextAsync()
  • Or reduce round trips with a single query or projection
  • Enabling MARS on the connection string does not make DbContext thread-safe; it only allows multiple active result sets on one connection
  • Bound parallelism: each branch holds a pooled connection (Max Pool Size 100 by default)

⏱ 30-second answer

A DbContext wraps one connection and one change tracker and allows one operation at a time; EF's concurrency detector throws when a second async operation starts before the first completes, usually from a shared context or a missing await. To run work in parallel, give each branch its own context (IDbContextFactory<T>.CreateDbContextAsync()), or combine the queries into one round trip. Never share a context across Task.WhenAll branches.

🔍 What the interviewer is checking

Checks understanding of DbContext concurrency and parallel patterns

↩ Usually asked after

More in Service Lifetimes

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me