"A second operation was started on this context" — the EF Core bug that only shows up under load
DEV Community
"A second operation was started on this context" — the EF Core bug that only shows up under load
In a hosted background service, a single scoped DbContext was being reused across parallel work items, and everything looked fine in local testing. Under real concurrency it produced intermittent `InvalidOperationException: A second operation was started on this context before a previous operation completed`. The cause was not an obvious `Task.WhenAll` over the context itself, but a fire-and-forget task that kept a captured reference alive after the scope had moved on. The fix was structural, not cosmetic: create one scope per unit of work, resolve the context inside it, and never let a DbContext outlive the scope that owns it. The takeaway is that EF Core thread-safety rules are about lifetime, and lifetime bugs hide until concurrency arrives.
0 comments
No comments yet.