Imagine a user opens a page that displays thousands of records. The browser sends an API request, and the ASP.NET Core application starts executing a database query.
Before the query finishes, the user navigates to another page or closes the browser tab.
The client no longer needs the response, but the database query might continue running. The application may still be waiting for the database, processing results, and consuming resources for a request that nobody is waiting for.
This situation becomes more serious when an application handles hundreds or thousands of concurrent requests.
Database connections remain occupied, unnecessary queries compete for database resources, and application performance can deteriorate even though users have already cancelled their requests.
ASP.NET Core provides a straightforward mechanism to address this problem: cancellation tokens.
By using HttpContext.RequestAborted and passing its cancellation token through controllers, services, repositories, and database operations, an application can stop unnecessary work when an HTTP request is aborted.
However, adding a cancellation token to a controller is only the beginning. The token must reach the actual database operation, and the application must understand what cancellation means for database writes, transactions, external API calls, and background processing.
Let's explore how to implement request cancellation properly in ASP.NET Core.
Understanding Why Cancelled Requests Can Continue Database Work
Consider a typical API endpoint:
[HttpGet("customers")]
public async Task<IActionResult> GetCustomers()
{
var customers = await _dbContext.Customers
.Where(x => x.IsActive)
.ToListAsync();
return Ok(customers);
}
This endpoint retrieves all active customers from the database.
Suppose the query takes five seconds to complete.
A user sends the request, waits for two seconds, and then closes the browser tab.
The browser stops waiting for the response, but that does not automatically guarantee that every operation started by the server will stop.
The database query may continue executing because the application has not explicitly connected the request's cancellation signal to the database operation.
This creates unnecessary work.
Consider a scenario where 100 users send expensive database queries and cancel them shortly afterward.
If the queries continue running, they can:
Occupy database connections unnecessarily.
Consume database CPU and memory.
Increase query execution time for other users.
Increase application resource consumption.
Create unnecessary network traffic between the application and database.
Reduce the application's ability to handle new requests.
The solution is to propagate cancellation from the HTTP request to the database operation.
Understanding CancellationToken in .NET
CancellationToken is a .NET mechanism for communicating a cancellation request between different parts of an application.
It does not forcibly terminate a thread or stop arbitrary code.
Instead, it provides a signal that an operation can observe and respond to.
For example:
public async Task ProcessAsync(
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
await Task.Delay(
TimeSpan.FromSeconds(10),
cancellationToken);
}
If the token is cancelled while Task.Delay is running, the operation throws an OperationCanceledException.
The important point is that the operation must support cancellation.
Passing a token to a method that ignores it does not automatically stop that method's work.
.NET asynchronous APIs commonly accept cancellation tokens for operations such as:
Reading and writing streams.
Executing database commands.
Sending HTTP requests.
Waiting for asynchronous operations.
Processing data asynchronously.
This allows cancellation to travel through multiple application layers.
Understanding HttpContext.RequestAborted
ASP.NET Core exposes a cancellation token through:
HttpContext.RequestAborted
This token notifies the application when the underlying HTTP request has been aborted.
For example, the request might be aborted because:
The client disconnects.
The browser closes the connection.
The client cancels the request.
The server aborts the request.
A configured request timeout expires.
The token can be passed to long-running operations so they can stop processing when the request is no longer active.
Consider this example:
[HttpGet("customers")]
public async Task<IActionResult> GetCustomers()
{
var customers = await _dbContext.Customers
.ToListAsync(HttpContext.RequestAborted);
return Ok(customers);
}
The database query now receives the request cancellation token.
If the request is aborted, EF Core passes the cancellation request to the underlying database provider.
There is one important detail: database providers may differ in how they implement and honor cancellation. A cancellation request does not guarantee that the database engine immediately stops executing a query.
Nevertheless, passing the token is an essential step toward avoiding unnecessary database work.
Using CancellationToken Directly in Controller Actions
ASP.NET Core provides a convenient way to receive the request cancellation token without accessing HttpContext directly.
You can add a CancellationToken parameter to a controller action:
[HttpGet("customers")]
public async Task<IActionResult> GetCustomers(
CancellationToken cancellationToken)
{
var customers = await _dbContext.Customers
.ToListAsync(cancellationToken);
return Ok(customers);
}
For controller actions, ASP.NET Core supplies the request cancellation token to this parameter.
This approach keeps the controller code clean and makes the dependency on cancellation explicit.
You can also use the same approach with Minimal APIs:
app.MapGet(
"/customers",
async (
AppDbContext dbContext,
CancellationToken cancellationToken) =>
{
var customers = await dbContext.Customers
.ToListAsync(cancellationToken);
return Results.Ok(customers);
});
In both examples, the database query receives the cancellation token associated with the incoming HTTP request.
For most application code, accepting a CancellationToken parameter is preferable to repeatedly accessing HttpContext.RequestAborted.
Propagating Cancellation Through Application Layers
Real applications rarely execute database queries directly inside controller actions.
A typical application might use the following structure:
HTTP Request
|
v
Controller
|
v
Application Service
|
v
Repository
|
v
Entity Framework Core
|
v
Database
If the cancellation token is not passed from one layer to the next, the cancellation signal may never reach the database.
Consider the following implementation.
An implementation that does not propagate cancellation
Controller:
[HttpGet("customers")]
public async Task<IActionResult> GetCustomers(
CancellationToken cancellationToken)
{
var customers = await _customerService.GetCustomersAsync();
return Ok(customers);
}
Service:
public async Task<List<Customer>> GetCustomersAsync()
{
return await _customerRepository.GetCustomersAsync();
}
Repository:
public async Task<List<Customer>> GetCustomersAsync()
{
return await _dbContext.Customers
.ToListAsync();
}
Although the controller receives a cancellation token, it never passes that token to the service.
The repository also does not receive a token.
Consequently, the database query cannot respond to the cancellation signal supplied by the request.
An implementation that propagates cancellation correctly
The solution is to accept the token in each method and pass it to the next operation.
Controller:
[HttpGet("customers")]
public async Task<IActionResult> GetCustomers(
CancellationToken cancellationToken)
{
var customers =
await _customerService.GetCustomersAsync(
cancellationToken);
return Ok(customers);
}
Service:
public async Task<List<Customer>> GetCustomersAsync(
CancellationToken cancellationToken)
{
return await _customerRepository
.GetCustomersAsync(cancellationToken);
}
Repository:
public async Task<List<Customer>> GetCustomersAsync(
CancellationToken cancellationToken)
{
return await _dbContext.Customers
.Where(x => x.IsActive)
.ToListAsync(cancellationToken);
}
Now the cancellation token travels through every application layer.
When the HTTP request is aborted, the database operation receives the cancellation signal.
This is one of the most important practices for building responsive ASP.NET Core APIs.
Stopping Entity Framework Core Queries
Entity Framework Core provides asynchronous query methods that accept a CancellationToken.
Some commonly used methods include:
ToListAsync()
FirstAsync()
FirstOrDefaultAsync()
SingleAsync()
SingleOrDefaultAsync()
AnyAsync()
CountAsync()
LongCountAsync()
SaveChangesAsync()
For example, consider an API that retrieves an order with its related customer and order items.
Without cancellation:
public async Task<Order?> GetOrderAsync(
int orderId)
{
return await _dbContext.Orders
.Include(x => x.Customer)
.Include(x => x.OrderItems)
.FirstOrDefaultAsync(x => x.Id == orderId);
}
With cancellation:
public async Task<Order?> GetOrderAsync(
int orderId,
CancellationToken cancellationToken)
{
return await _dbContext.Orders
.Include(x => x.Customer)
.Include(x => x.OrderItems)
.FirstOrDefaultAsync(
x => x.Id == orderId,
cancellationToken);
}
The second implementation allows the database operation to receive the cancellation request.
Applying cancellation to projections
Projection is commonly used to retrieve only the fields required by an API.
For example:
public async Task<List<OrderResponse>> GetOrdersAsync(
CancellationToken cancellationToken)
{
return await _dbContext.Orders
.Where(x => x.Status == "Completed")
.Select(x => new OrderResponse
{
OrderId = x.Id,
CustomerName = x.Customer.Name,
TotalAmount = x.TotalAmount
})
.ToListAsync(cancellationToken);
}
The token is passed to ToListAsync(), which executes the database query.
This is important because projection alone does not provide cancellation. The asynchronous operation that executes the query must receive the token.
Applying cancellation to SaveChangesAsync
EF Core also supports cancellation when saving changes:
public async Task CreateCustomerAsync(
Customer customer,
CancellationToken cancellationToken)
{
_dbContext.Customers.Add(customer);
await _dbContext.SaveChangesAsync(
cancellationToken);
}
However, database writes require additional consideration.
Cancelling a database write does not always mean that nothing was committed.
For example, the database might successfully commit a transaction just before the application receives the cancellation signal. The application might then fail to return the response to the client.
From the client's perspective, the operation may appear unsuccessful even though the database change was committed.
This is why important write operations should be designed with idempotency and transaction management in mind.
We will examine this problem later in the article.
Stopping Dapper Database Queries
Not every ASP.NET Core application uses Entity Framework Core.
Many applications use Dapper with SQL Server, PostgreSQL, or another relational database.
Dapper supports cancellation through its CommandDefinition type.
Consider the following repository method without cancellation:
public async Task<IEnumerable<Customer>> GetCustomersAsync()
{
const string sql = """
SELECT Id, Name, Email
FROM Customers
WHERE IsActive = 1
""";
return await _connection.QueryAsync<Customer>(sql);
}
The query executes without receiving the request cancellation token.
To support cancellation, create a CommandDefinition and pass the token:
public async Task<IEnumerable<Customer>> GetCustomersAsync(
CancellationToken cancellationToken)
{
const string sql = """
SELECT Id, Name, Email
FROM Customers
WHERE IsActive = 1
""";
var command = new CommandDefinition(
commandText: sql,
cancellationToken: cancellationToken);
return await _connection
.QueryAsync<Customer>(command);
}
The controller and service should pass the same token through to this repository method.
Dapper then passes the cancellation information to the underlying ADO.NET command.
The actual cancellation behavior still depends on the database provider and driver.
Using ADO.NET directly
If an application uses ADO.NET without Dapper or EF Core, asynchronous command execution also supports cancellation.
For example:
public async Task<List<Customer>> GetCustomersAsync(
SqlConnection connection,
CancellationToken cancellationToken)
{
const string sql = """
SELECT Id, Name, Email
FROM Customers
WHERE IsActive = 1
""";
await using var command =
new SqlCommand(sql, connection);
var customers = new List<Customer>();
await using var reader =
await command.ExecuteReaderAsync(
cancellationToken);
while (await reader.ReadAsync(
cancellationToken))
{
customers.Add(new Customer
{
Id = reader.GetInt32(0),
Name = reader.GetString(1),
Email = reader.GetString(2)
});
}
return customers;
}
Notice that the token is passed to both ExecuteReaderAsync() and ReadAsync().
The first token allows cancellation during command execution. The second allows cancellation while reading the result set.
For applications that process large result sets, this distinction matters.
Combining Request Cancellation With an Application Timeout
Request cancellation and operation timeouts solve related but different problems.
Request cancellation tells the application that the client or server has aborted the request.
An application timeout limits how long an individual operation is allowed to run.
For example, a database query might be allowed to run for a maximum of 15 seconds even if the HTTP request remains active.
You can combine both requirements by using a linked cancellation token.
public async Task<List<Customer>> GetCustomersAsync(
CancellationToken requestCancellationToken)
{
using var timeoutCts =
new CancellationTokenSource(
TimeSpan.FromSeconds(15));
using var linkedCts =
CancellationTokenSource.CreateLinkedTokenSource(
requestCancellationToken,
timeoutCts.Token);
return await _dbContext.Customers
.Where(x => x.IsActive)
.ToListAsync(linkedCts.Token);
}
The linked token is cancelled when either:
This provides two independent cancellation conditions.
However, avoid adding a separate timeout to every repository method without considering the application's overall timeout policy.
For database operations, also configure the appropriate database command timeout. A cancellation token and a command timeout are separate controls, and the database provider determines how they interact.
Understanding request timeouts in ASP.NET Core
ASP.NET Core also provides request timeout middleware.
It can be used to configure timeout policies for specific endpoints.
For example:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRequestTimeouts(options =>
{
options.AddPolicy(
"DatabaseTimeout",
TimeSpan.FromSeconds(20));
});
var app = builder.Build();
app.UseRequestTimeouts();
app.MapGet(
"/customers",
async (
AppDbContext dbContext,
CancellationToken cancellationToken) =>
{
var customers = await dbContext.Customers
.ToListAsync(cancellationToken);
return Results.Ok(customers);
})
.WithRequestTimeout("DatabaseTimeout");
app.Run();
When the configured request timeout expires, ASP.NET Core signals cancellation through the request cancellation token.
This means the database query can receive the same cancellation signal without requiring a separate timeout implementation inside the repository.
Choose timeout values based on the actual work performed by each endpoint. A report-generation endpoint and a simple lookup endpoint may need different timeout policies.
Handling Cancellation Exceptions Correctly
When an asynchronous operation observes a cancelled token, it commonly throws an OperationCanceledException.
Some APIs may throw the more specific TaskCanceledException, which derives from OperationCanceledException.
Consider the following code:
try
{
var customers = await _dbContext.Customers
.ToListAsync(cancellationToken);
return Ok(customers);
}
catch (Exception ex)
{
_logger.LogError(
ex,
"Unable to retrieve customers.");
return StatusCode(500);
}
This implementation catches every exception, including cancellation exceptions.
That can create misleading error logs because a normal client disconnect may be reported as an application failure.
A better approach is to handle expected cancellation separately.
try
{
var customers = await _dbContext.Customers
.ToListAsync(cancellationToken);
return Ok(customers);
}
catch (OperationCanceledException)
when (cancellationToken.IsCancellationRequested)
{
_logger.LogInformation(
"Customer request was cancelled.");
throw;
}
catch (Exception ex)
{
_logger.LogError(
ex,
"Unable to retrieve customers.");
return StatusCode(500);
}
The cancellation exception is not treated as an unexpected application error.
The exception is rethrown so that ASP.NET Core can complete the aborted request appropriately.
There is an important distinction here.
An OperationCanceledException does not always mean that the client disconnected.
It can also be caused by:
An application timeout.
A manually cancelled operation.
A linked cancellation token.
A downstream operation's own cancellation policy.
Therefore, inspect the relevant cancellation token before deciding how to log or handle the exception.
Also, do not assume that a disconnected client can receive an HTTP response. Once the connection has been aborted, the server may no longer be able to deliver a response.
Understanding Cancellation in Database Transactions
Database writes require more careful handling than read-only queries.
Consider an API that transfers money between two accounts.
The application performs the following operations:
Read the source account.
Read the destination account.
Deduct the amount from the source account.
Add the amount to the destination account.
Save the changes.
Return a successful response.
What happens if the user closes the browser while the database transaction is executing?
The application may receive a cancellation request while the database operation is in progress.
It is tempting to assume that cancellation means the complete operation has been rolled back.
That assumption is unsafe.
The database may already have committed the transaction, or the commit may have succeeded even though the application did not receive confirmation.
This creates an important distributed-systems problem: the application may not know whether the operation completed successfully.
Use transactions for related database operations
For operations that must succeed or fail together, use a database transaction.
For example:
public async Task TransferAsync(
int fromAccountId,
int toAccountId,
decimal amount,
CancellationToken cancellationToken)
{
await using var transaction =
await _dbContext.Database.BeginTransactionAsync(
cancellationToken);
var sourceAccount =
await _dbContext.Accounts
.FirstOrDefaultAsync(
x => x.Id == fromAccountId,
cancellationToken);
var destinationAccount =
await _dbContext.Accounts
.FirstOrDefaultAsync(
x => x.Id == toAccountId,
cancellationToken);
if (sourceAccount == null ||
destinationAccount == null)
{
throw new InvalidOperationException(
"Account not found.");
}
if (sourceAccount.Balance < amount)
{
throw new InvalidOperationException(
"Insufficient balance.");
}
sourceAccount.Balance -= amount;
destinationAccount.Balance += amount;
await _dbContext.SaveChangesAsync(
cancellationToken);
await transaction.CommitAsync(
cancellationToken);
}
The transaction ensures that the related database changes are grouped into one transactional operation.
However, this example still needs additional business validation, concurrency protection, and idempotency before it is suitable for a real payment system.
Understand the commit ambiguity problem
Consider this sequence:
Client sends request
|
v
Application starts transaction
|
v
Database updates accounts
|
v
Database commits transaction
|
v
Client disconnects
|
v
Application cannot return response
The client may retry the transfer because it did not receive a successful response.
If the application processes the request again without checking whether the original operation succeeded, the user could be charged twice.
Cancellation tokens alone cannot solve this problem.
Use idempotency for important write operations
For financial transactions, orders, payments, and other critical operations, use an idempotency key.
The client sends a unique identifier with the request.
The application records the identifier as part of the transaction and prevents the same logical operation from being executed again.
A simplified request might look like this:
POST /api/payments
Idempotency-Key: 9a12f3d8-1234-4567-8901-abcdef123456
Content-Type: application/json
The application should:
Check whether the idempotency key has already been processed.
Return the previous result if the operation is already complete.
Otherwise, execute the operation.
Store the result and idempotency key in the same database transaction.
Return the result to the client.
The database should enforce uniqueness for the idempotency key within the appropriate business scope.
This protects the operation when clients retry after timeouts, disconnects, or uncertain responses.
For important writes, do not simply remove cancellation support from every database call. Instead, design the operation so that its outcome can be safely determined and retried.
Using Cancellation Tokens With HttpClient
Database operations are not the only work that should respond to request cancellation.
An API might call another service before returning a response.
For example, an order API might retrieve customer information from an external service.
Without cancellation:
public async Task<Customer?> GetCustomerAsync(
int customerId)
{
return await _httpClient.GetFromJsonAsync<Customer>(
$"customers/{customerId}");
}
If the original HTTP request is aborted, the external HTTP request may continue unnecessarily.
Pass the cancellation token to the HTTP client operation:
public async Task<Customer?> GetCustomerAsync(
int customerId,
CancellationToken cancellationToken)
{
return await _httpClient.GetFromJsonAsync<Customer>(
$"customers/{customerId}",
cancellationToken);
}
The controller should pass its request cancellation token to the service.
This allows cancellation to propagate through the application and into the downstream HTTP request.
The same principle applies when an API calls multiple services, reads files, or performs other asynchronous work.
Handling Cancellation in Parallel Operations
Some API endpoints retrieve information from multiple sources simultaneously.
For example, a dashboard might request:
Customer information.
Recent orders.
Payment summaries.
Notification counts.
You can use Task.WhenAll() to execute independent operations concurrently.
Each operation should receive the same cancellation token.
public async Task<DashboardResponse> GetDashboardAsync(
CancellationToken cancellationToken)
{
var customersTask =
_customerService.GetSummaryAsync(
cancellationToken);
var ordersTask =
_orderService.GetRecentOrdersAsync(
cancellationToken);
var paymentsTask =
_paymentService.GetSummaryAsync(
cancellationToken);
await Task.WhenAll(
customersTask,
ordersTask,
paymentsTask);
return new DashboardResponse
{
Customers = await customersTask,
Orders = await ordersTask,
Payments = await paymentsTask
};
}
When the request is cancelled, each operation has an opportunity to stop.
However, Task.WhenAll() does not automatically cancel the other tasks just because one task fails or is cancelled.
If one operation fails independently, the remaining operations may continue unless they receive a cancellation signal.
For more complex workflows, create a linked cancellation token source and define an explicit policy for cancelling related tasks.
Also remember that EF Core does not support multiple parallel operations on the same DbContext instance. If the dashboard services use the same context instance, the parallel database operations can fail.
Use separate context instances or execute those operations sequentially, depending on the architecture and performance requirements.
Should Cancellation Tokens Be Used for Background Jobs?
One of the most common mistakes is passing an HTTP request cancellation token into work that must continue after the request finishes.
Consider an endpoint that accepts an order and then generates an invoice.
A developer might write:
await _invoiceService.GenerateAsync(
orderId,
cancellationToken);
If invoice generation is a long-running task and the user disconnects, the operation may be cancelled.
That may not be the desired behavior.
The important question is whether the work belongs to the HTTP request or must continue independently.
Request-scoped work
Use the request cancellation token for work that exists only to produce the current response.
Examples include:
Retrieving customer information.
Searching products.
Generating a response from database query results.
Calling another API to retrieve information.
Reading a file to return it to the client.
When the request is no longer needed, the work can usually stop.
Background work
Use a background processing mechanism for work that must continue independently of the HTTP connection.
Examples include:
Sending emails.
Generating invoices.
Processing uploaded documents.
Publishing business events.
Running lengthy reports.
Synchronizing data with external systems.
Instead of performing the complete operation inside the HTTP request, enqueue a durable job.
For example:
[HttpPost("orders/{orderId}/invoice")]
public async Task<IActionResult> GenerateInvoice(
int orderId,
CancellationToken cancellationToken)
{
var jobId = await _invoiceQueue.EnqueueAsync(
orderId,
cancellationToken);
return Accepted(new
{
JobId = jobId,
Status = "Queued"
});
}
The endpoint accepts the work and returns a response indicating that processing has been queued.
A background worker processes the job independently of the original HTTP request.
The queue operation itself uses the request token because the application should not continue trying to accept a job after the request has been abandoned.
Once the job has been durably accepted, the worker should use its own lifetime and cancellation policies rather than the original request token.
For important work, use a durable queue or database-backed job system instead of an in-memory queue that can lose jobs when the application restarts.
Testing Request Cancellation
Cancellation logic should be tested rather than assumed to work.
A simple way to test the behavior is to create an endpoint that performs a long-running asynchronous operation.
[HttpGet("long-running")]
public async Task<IActionResult> LongRunning(
CancellationToken cancellationToken)
{
try
{
await Task.Delay(
TimeSpan.FromSeconds(30),
cancellationToken);
return Ok("Operation completed.");
}
catch (OperationCanceledException)
when (cancellationToken.IsCancellationRequested)
{
_logger.LogInformation(
"Request was cancelled.");
throw;
}
}
Send a request to the endpoint and cancel it before the 30-second delay completes.
The operation should observe the cancellation token and stop waiting.
You can also test database cancellation by executing a deliberately long-running query in a controlled test environment and cancelling the HTTP request.
For example, SQL Server supports WAITFOR DELAY:
WAITFOR DELAY '00:00:30';
Use this only in a development or test environment.
Send a request to an endpoint that executes this statement with a cancellation token. Cancel the request and observe whether the database command stops.
The result depends on the database provider, driver, and command execution path, so verify the behavior using database monitoring tools rather than relying only on the application log.
What should be tested?
A useful cancellation test plan includes:
Cancelling a request before a database query starts.
Cancelling while a database query is executing.
Cancelling while reading a large result set.
Cancelling a downstream HTTP request.
Cancelling an operation during a transaction.
Allowing a query to complete normally.
Triggering an application timeout.
Retrying a write operation after an uncertain response.
These tests help identify missing cancellation-token propagation and unexpected behavior in database providers.
Common Mistakes to Avoid
Even when developers understand cancellation tokens, several implementation mistakes can prevent cancellation from working correctly.
Receiving a token but not passing it forward
This is one of the most common mistakes.
public async Task<List<Customer>> GetCustomersAsync(
CancellationToken cancellationToken)
{
return await _dbContext.Customers.ToListAsync();
}
The method receives a token but never uses it.
Correct implementation:
public async Task<List<Customer>> GetCustomersAsync(
CancellationToken cancellationToken)
{
return await _dbContext.Customers.ToListAsync(
cancellationToken);
}
Every layer should pass the token to the next asynchronous operation that supports cancellation.
Assuming cancellation forcibly terminates database execution
Cancellation is cooperative.
The application requests cancellation, but the database provider and database engine determine how quickly the operation stops.
Do not assume that a cancelled HTTP request always means the database query has already stopped.
Verify provider behavior and monitor actual database execution.
Catching every exception and returning HTTP 500
A normal request cancellation should not automatically be reported as an application failure.
Handle expected cancellation separately and avoid logging every cancellation as an error.
Passing the HTTP token to independent background work
An email, invoice, or other durable business operation may need to continue after the user disconnects.
Use a background processing mechanism when work must outlive the HTTP request.
Assuming a cancelled write was rolled back
A cancellation signal can arrive after the database has committed a transaction.
Use transactions, idempotency keys, and reliable operation tracking for important writes.
Using the same DbContext for parallel queries
EF Core does not support multiple parallel operations on one DbContext instance.
Use separate contexts or execute operations sequentially.
Ignoring downstream operations
Cancelling a database query is not enough if the application continues calling external APIs, processing files, or performing other expensive operations.
Propagate cancellation through the complete request-processing workflow.
Production Best Practices
For production ASP.NET Core applications, use the following practices when implementing cancellation.
Area | Recommended practice |
|---|
Controllers | Accept a CancellationToken parameter |
Services | Pass the token to downstream methods |
Repositories | Forward the token to database operations |
EF Core | Use cancellation-aware asynchronous methods |
Dapper | Use CommandDefinition with a cancellation token |
ADO.NET | Pass the token to asynchronous command and reader methods |
HttpClient | Pass the token to outgoing HTTP requests |
Timeouts | Configure appropriate request and database operation limits |
Exceptions | Handle expected cancellation separately |
Transactions | Design writes with clear transaction boundaries |
Important writes | Use idempotency to handle retries safely |
Background work | Use independent background processing and cancellation policies |
Monitoring | Track cancelled operations and database execution |
A few additional recommendations are worth keeping in mind.
First, make cancellation tokens part of the application's service and repository method contracts. This makes cancellation support easier to maintain as the application grows.
Second, avoid accessing HttpContext from repository classes. The web layer should obtain the request cancellation token and pass it into application services.
Third, do not store HttpContext or its request-specific data for use after the HTTP request completes. The context is valid only during the active request.
Finally, measure the actual results. Monitor database query duration, active connections, cancelled commands, and application request latency to determine whether cancellation is reducing unnecessary work.
Conclusion
A cancelled HTTP request should not continue consuming application and database resources unnecessarily.
ASP.NET Core provides HttpContext.RequestAborted to notify the application when a request is aborted. By passing this cancellation token through controllers, services, repositories, and database operations, applications can respond to cancellation more effectively.
Entity Framework Core, Dapper, ADO.NET, and HttpClient all provide ways to propagate cancellation to their asynchronous operations.
However, cancellation must be implemented with care. Database providers may not immediately stop executing a query, cancelled writes can have uncertain outcomes, and important business operations should not depend on the lifetime of an HTTP connection.
The best approach is to propagate request cancellation through request-scoped work, use appropriate timeout policies, protect important writes with transactions and idempotency, and move independent long-running operations into durable background processing.
These practices help ASP.NET Core applications use database resources more efficiently and remain reliable under heavy request traffic.
Join the conversation! Your thoughts help the community grow.