Handling DbContext Threading Issues in .NET Core with EF Core
net | 2021-08-20
🚩 The Problem
While working on a .NET Core application using Entity Framework Core (EF Core) as ORM,
we faced some threading issues due to multiple DbContext
usage, JWT authentication, and API concurrency.
📈 Request & Response Flow
Request →
JWT Middleware to grab user object →
Authorization Filter to stop multiple logins →
Touch Controller →
Repository →
Execute Query →
Response
🛑 Issue and Solution
Common Exceptions
1. Connection Closed Exception
An exception occurred while **iterating over** the results of a query for context type.
The connection is closed
- Cause: A queryable object was still in memory while a second query was attempted.
- Solution: Always ensure you materialize (e.g.,
.ToList()
,.FirstOrDefault()
) any queryable object before running another query.
2. Parallel Operation Exception
One or more errors occurred. (A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext.)
- Cause: EF Core does not allow multiple parallel operations on the same
DbContext
. - Solution:
- Always
await
asynchronous operations before making another database call. - Do not share the same
DbContext
across threads.
- Always
🛠️ Troubleshooting Tips
- ✅ Reduce API calls: Consolidate similar frontend requests to minimize concurrent database usage.
- ✅ Await all async calls: Ensure each query is awaited before proceeding.
- ✅ Register DbContext as Transient:
services.AddDbContext<AppDbContext>(options => options.UseSqlServer(connectionString), ServiceLifetime.Transient);
- ✅ Use IServiceScopeFactory: Create a fresh scope for parallel tasks if unavoidable.