Introduction
Database access in ASP.NET Core applications usually involves network and disk waits. During that wait, the CPU is not performing intensive computation; however, a synchronous API keeps the request thread blocked until the database responds. As traffic increases, many threads can remain blocked, creating Thread Pool pressure. Request latency grows, new requests wait in queues and application resources are used inefficiently.
EF Core provides asynchronous APIs such as ToListAsync, FirstOrDefaultAsync, AnyAsync, CountAsync and SaveChangesAsync to reduce this type of blocking. However, replacing a method name is not enough. The asynchronous operation must actually be awaited, the entire call chain should remain asynchronous, the cancellation token should be propagated and concurrent operations must not be started on the same DbContext instance.
This lesson examines these problems through a small web application scenario.
1. Why can synchronous calls create Thread Pool pressure?
The following service method may work correctly, but the request thread remains blocked while the database responds:
public List<ProductSummary> GetActiveProducts()
{
return _db.Products
.Where(p => p.IsActive)
.Select(p => new ProductSummary(p.Id, p.Name))
.ToList();
}ToList executes the query immediately and returns the materialized results. When many requests arrive at the same time, each request can hold a thread while waiting for the database. This does not always produce an immediate exception, but it can increase latency, consume more Thread Pool threads and reduce throughput.
The asynchronous version allows the thread to be used for other work while database I/O is pending:
public async Task<List<ProductSummary>> GetActiveProductsAsync(
CancellationToken cancellationToken)
{
return await _db.Products
.Where(p => p.IsActive)
.Select(p => new ProductSummary(p.Id, p.Name))
.ToListAsync(cancellationToken);
}In this example, Where and Select build the query; execution occurs at ToListAsync. EF Core asynchronous methods make database I/O waits non-blocking. They do not automatically accelerate CPU-bound work; their main benefit here is more efficient handling of I/O waits.
2. Incorrect await patterns
2.1. Calling an async method without awaiting it
In the following code, the operation is started but completion is not observed:
public async Task CreateProductAsync(Product product)
{
_db.Products.Add(product);
_db.SaveChangesAsync();
}The Task returned by SaveChangesAsync is ignored. The HTTP request may finish while the database operation is still running. If the operation fails, the caller cannot reliably handle the exception. Another operation may also begin on the same DbContext.
The corrected version is:
public async Task CreateProductAsync(
Product product,
CancellationToken cancellationToken)
{
_db.Products.Add(product);
await _db.SaveChangesAsync(cancellationToken);
}A method returning Task can be awaited by its caller. The response is not produced before the operation completes, and exceptions can be observed by the calling layer.
2.2. Consuming an async result synchronously
The following pattern turns asynchronous code back into blocking code:
var products = _service.GetActiveProductsAsync(token).Result;Using .Wait() has the same fundamental problem. Although ASP.NET Core does not have exactly the same synchronization-context behavior as older application models, blocking still increases Thread Pool pressure and wastes the advantages of asynchronous I/O. Keep the call chain asynchronous instead:
public async Task<IActionResult> Get(CancellationToken cancellationToken)
{
var products = await _service.GetActiveProductsAsync(cancellationToken);
return Ok(products);
}2.3. Using async void
Application code should avoid async void. Such methods cannot be awaited, and exceptions cannot be handled by the calling layer in the normal task-based way. Except for special cases such as event handlers, return Task or Task<T>:
public async Task UpdateProductAsync(
Product product,
CancellationToken cancellationToken)
{
_db.Products.Update(product);
await _db.SaveChangesAsync(cancellationToken);
}3. Building an end-to-end asynchronous method chain
Asynchronous execution should not stop at the repository layer. Controllers, services and data-access components should preserve the same flow. The following example finds a product, updates it and saves the change:
public sealed class ProductService
{
private readonly StoreDbContext _db;
public ProductService(StoreDbContext db) => _db = db;
public async Task<bool> RenameAsync(
int id,
string name,
CancellationToken cancellationToken)
{
var product = await _db.Products
.FirstOrDefaultAsync(p => p.Id == id, cancellationToken);
if (product is null)
return false;
product.Name = name;
await _db.SaveChangesAsync(cancellationToken);
return true;
}
}The controller receives the HTTP request cancellation token and passes it to the service:
[HttpPut("{id:int}/name")]
public async Task<IActionResult> Rename(
int id,
RenameProductRequest request,
CancellationToken cancellationToken)
{
var updated = await _products.RenameAsync(
id, request.Name, cancellationToken);
return updated ? NoContent() : NotFound();
}If the client disconnects or the server terminates the request, the token can be canceled. Passing it through every layer reduces unnecessary work in long-running queries.
4. Why is CancellationToken important?
A token is not merely a decorative parameter. If it is not passed to the database operation, EF Core cannot propagate the cancellation request to the query:
var products = await _db.Products
.Where(p => p.IsActive)
.ToListAsync();The preferred version is:
var products = await _db.Products
.Where(p => p.IsActive)
.ToListAsync(cancellationToken);The same principle applies to FirstOrDefaultAsync, SingleOrDefaultAsync, AnyAsync, CountAsync and SaveChangesAsync. Cancellation is not the same as failure. When an OperationCanceledException is raised, the application can treat it as a normal request cancellation, but it should not catch and silently ignore every exception.
try
{
await _service.RenameAsync(id, request.Name, cancellationToken);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
return new EmptyResult();
}ASP.NET Core normally handles an aborted HTTP request appropriately. If custom logging is used, a user cancellation should not be reported as a database outage.
5. Concurrent async queries on the same DbContext
Using asynchronous APIs does not mean that unlimited parallelism is allowed on one DbContext. EF Core does not support multiple operations executing concurrently on the same context instance.
The following code is unsafe:
var categoriesTask = _db.Categories
.AsNoTracking()
.ToListAsync(cancellationToken);
var productsTask = _db.Products
.AsNoTracking()
.ToListAsync(cancellationToken);
await Task.WhenAll(categoriesTask, productsTask);AsNoTracking can reduce tracking overhead, but it does not make DbContext thread-safe. Both queries start concurrently on the same context, so an exception such as “A second operation started on this context before a previous operation completed” may occur.
The simplest fix is to await operations sequentially:
var categories = await _db.Categories
.AsNoTracking()
.ToListAsync(cancellationToken);
var products = await _db.Products
.AsNoTracking()
.ToListAsync(cancellationToken);If genuine parallel execution is required, each operation must use a separate DbContext instance. An appropriate lifetime configuration and IDbContextFactory<StoreDbContext> can be considered. However, parallelism also consumes database connections and server capacity, so it should be introduced only when measurement demonstrates a real need.
6. An incorrect and corrected web application example
The incorrect version has three problems: synchronous ToList, an unawaited SaveChangesAsync and concurrent queries on the same context:
public async Task<DashboardDto> GetDashboardAsync()
{
var products = _db.Products.ToList();
var categoriesTask = _db.Categories.ToListAsync();
var brandsTask = _db.Brands.ToListAsync();
await _db.SaveChangesAsync();
return new DashboardDto(products, await categoriesTask, await brandsTask);
}Calling save during a read-only dashboard operation is also suspicious from a design perspective. The corrected version uses the token, executes queries sequentially on the same context and removes the unnecessary save:
public async Task<DashboardDto> GetDashboardAsync(
CancellationToken cancellationToken)
{
var products = await _db.Products
.AsNoTracking()
.Where(p => p.IsActive)
.Select(p => new ProductSummary(p.Id, p.Name))
.ToListAsync(cancellationToken);
var categories = await _db.Categories
.AsNoTracking()
.Select(c => new CategorySummary(c.Id, c.Name))
.ToListAsync(cancellationToken);
var brands = await _db.Brands
.AsNoTracking()
.Select(b => new BrandSummary(b.Id, b.Name))
.ToListAsync(cancellationToken);
return new DashboardDto(products, categories, brands);
}7. Common mistakes
- Marking everything async: If a method performs no actual asynchronous operation, adding
asyncalone provides no meaningful benefit. - Performing large CPU work after ToListAsync: Materializing a large result set is still expensive. Filtering and projection should happen in SQL whenever possible.
- Keeping CancellationToken only in the controller: If the token is not passed through the service and repository layers, the query cannot be canceled promptly.
- Using Task.WhenAll with a shared context: Parallel operations require separate context instances.
- Silently swallowing exceptions: Errors from
SaveChangesAsyncshould be logged and the failed workflow should be explicit. - Running async database work as fire-and-forget: After the request ends, a scoped
DbContextmay be disposed while the background operation is still using it.
8. Short practice exercise
- Write a synchronous method that returns active products and explain why it can become problematic under high traffic.
- Change the method to return
Task<List<ProductSummary>>. - Propagate the controller's
CancellationTokenintoToListAsync. - Run two queries with
Task.WhenAllon the sameDbContextand observe the resulting behavior. - Fix the problem by awaiting the queries sequentially. Discuss when using two contexts through
IDbContextFactorywould be justified. - Verify that a canceled request is not logged as a database failure.
Conclusion
Asynchronous programming in EF Core is more than replacing synchronous method names with their async counterparts. Query-executing methods must be awaited, the call chain should remain asynchronous and the CancellationToken should reach the EF Core operation. Using Result, Wait, async void or fire-and-forget database work can cause latency, unobserved exceptions and resource-lifetime problems in web applications.
The most important rule is never to run concurrent operations on the same DbContext. Sequential awaits are sufficient in many cases. When true parallelism is necessary, use a separate context for each operation and control resource consumption carefully. Applying these principles reduces Thread Pool pressure, makes cancellation predictable and prevents difficult-to-diagnose asynchronous failures in production.
Sources
- https://learn.microsoft.com/en-us/ef/core/miscellaneous/async
- https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/
- https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/async-return-types
- https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/task-cancellation