Async best practices in EF Core
The basic rule - all I/O should be async
// ✅ Poprawnie
var order = await _context.Orders.FirstOrDefaultAsync(o => o.Id == id);
var count = await _context.Orders.CountAsync();
var exists = await _context.Orders.AnyAsync(o => o.Status == "Pending");
await _context.SaveChangesAsync();
// ❌ Wrong - blocks a thread, wastes throughput in Web API under load
var order = _context.Orders.FirstOrDefault(o => o.Id == id);
As we discussed earlier - a synchronous I/O call blocks a thread from the thread pool for the whole duration of the database query (it may be milliseconds, but with heavy traffic it adds up). Async lets the thread return to the pool and serve another request while we wait for the database.
Trap #1: Never share one DbContext between parallel tasks
// ❌ ERROR - DbContext is NOT thread-safe (as we discussed with Singleton/thread-safety)
var task1 = _context.Orders.ToListAsync();
var task2 = _context.Customers.ToListAsync();
await Task.WhenAll(task1, task2); // InvalidOperationException - "A second operation was started..."
// ✅ Correct - separate scopes/DbContexts for parallel operations
using var scope1 = _scopeFactory.CreateScope();
using var scope2 = _scopeFactory.CreateScope();
var context1 = scope1.ServiceProvider.GetRequiredService<AppDbContext>();
var context2 = scope2.ServiceProvider.GetRequiredService<AppDbContext>();
var task1 = context1.Orders.ToListAsync();
var task2 = context2.Customers.ToListAsync();
await Task.WhenAll(task1, task2); // OK - different DbContext instances
This ties directly back to what we said about IServiceScopeFactory and the Scoped lifetime - DbContext is Scoped precisely because it isn't thread-safe, and trying to share it between parallel tasks (even within the same request!) will throw an exception.
Trap #2: ConfigureAwait(false) in the data layer
public class OrderRepository
{
public async Task<Order> GetByIdAsync(int id)
{
// As we said with SynchronizationContext - the data layer/services
// do NOT touch the UI, so ConfigureAwait(false) makes sense here
return await _context.Orders
.FirstOrDefaultAsync(o => o.Id == id)
.ConfigureAwait(false);
}
}
Trap #3: .Result/.Wait() - blocking on asynchronous code
// ❌ NEVER - a risk of deadlock (as in the WPF scenario we discussed)
var order = _context.Orders.FirstOrDefaultAsync(o => o.Id == id).Result;
// ✅ Async all the way
var order = await _context.Orders.FirstOrDefaultAsync(o => o.Id == id);
Trap #4: IEnumerable vs IQueryable with async
// ❌ A problem - if the variable's type is IEnumerable, the filter will NOT reach SQL
IEnumerable<Order> orders = _context.Orders;
var filtered = orders.Where(o => o.Status == "Pending"); // IN MEMORY, after fetching EVERYTHING
var list = filtered.ToList(); // synchronicznie! (IEnumerable nie ma ToListAsync)
// ✅ Correct - IQueryable to the end, asynchronous materialisation
IQueryable<Order> orders = _context.Orders;
var filtered = orders.Where(o => o.Status == "Pending"); // trafia do SQL WHERE
var list = await filtered.ToListAsync();
CancellationToken - propagation through the whole async chain
[HttpGet]
public async Task<ActionResult<List<OrderDto>>> GetOrders(CancellationToken cancellationToken)
{
var orders = await _context.Orders.ToListAsync(cancellationToken); // przekazane DALEJ do EF Core
return Ok(orders);
}
If the user closes the browser tab/aborts the request, ASP.NET Core automatically cancels this token - EF Core aborts the SQL query in progress, instead of waiting for it to finish and throwing the result away. This really offloads the database under heavy traffic.
Summary - a best-practices checklist
- Always
async/awaitfor EF Core operations (ToListAsync,FirstOrDefaultAsync,SaveChangesAsync) - Never share one
DbContextbetween parallel tasks - create separate scopes ConfigureAwait(false)in the repository/service layer (doesn't apply to UI code, as we discussed with WPF)- Never
.Result/.Wait()on EF Core code - a risk of deadlock - Keep
IQueryableuntil materialisation (ToListAsync), so the filter/pagination reach SQL - Propagate the
CancellationTokenthrough the whole call chain