What is a DbContext, and why should it generally not be shared across multiple concurrent operations?
Short answer
DbContext represents a session with the database, tracking a unit of work's entities and managing the underlying database connection -- it's explicitly not thread-safe, meaning a single DbContext instance must not be used concurrently from multiple threads (like parallel…
Advertisement
AModel answer
DbContext represents a session with the database, tracking a unit of work's entities and managing the underlying database connection -- it's explicitly not thread-safe, meaning a single DbContext instance must not be used concurrently from multiple threads (like parallel Task.WhenAll calls sharing one context), which would corrupt its internal state; the standard pattern is one DbContext per unit of work (typically one per HTTP request in web apps, enforced naturally by its Scoped DI registration).
// WRONG: sharing one DbContext across concurrent operations
var tasks = ids.Select(id => context.Products.FindAsync(id)); // same context, concurrent access -- unsafe!
await Task.WhenAll(tasks);
// CORRECT: each operation gets its own context/scope, or operations run sequentially
foreach (var id in ids) {
var product = await context.Products.FindAsync(id);
}Real-world example
A bug causing intermittent, hard-to-reproduce data corruption is traced to a background job that incorrectly shared a single DbContext instance across multiple parallel Task.WhenAll operations, violating DbContext's fundamental single-threaded usage contract.
Likely follow-ups
- What exception or symptom typically results from concurrent DbContext access?
- How does DbContext's Scoped DI lifetime naturally enforce one-per-request usage?
Related topics