LESSON 2 OF 13

Async/Await and Concurrency in the ASP.NET Core Request Pipeline

Learn how to use async/await across ASP.NET Core request layers, remove synchronous blocking, propagate CancellationToken, and measure the performance impact.

45 dk 71

Introduction

ASP.NET Core performance is not determined only by how quickly a single operation completes. It also depends on how many requests can be processed concurrently, how efficiently request threads are used while waiting, and how stable response times remain under load. Operations that access a database, file system, HTTP service, or message broker usually involve I/O waits. Blocking a thread during those waits can force the application to create more ThreadPool threads and may eventually lead to ThreadPool starvation.

In this lesson, we will build an end-to-end asynchronous flow across controllers, services, and repositories. We will examine why synchronous waiting with .Result, .Wait(), and GetAwaiter().GetResult() is problematic, then use CancellationToken to stop unnecessary work when a client disconnects. Finally, we will compare incorrect and correct implementations using performance measurements rather than relying only on code inspection.

Core principle: When you call an asynchronous API, propagate its result upward with await. Do not turn an asynchronous flow back into a synchronous one at a higher layer.

How async/await works

The async keyword indicates that a method can contain asynchronous operations; it does not automatically move the work to another thread. The await keyword suspends the current method until the awaited Task completes. While an I/O operation is in progress, the ASP.NET Core thread can be released and used to process another request. When the operation completes, execution continues.

Therefore, await does not magically speed up CPU-bound work. Serializing a large object, running a complex algorithm, or processing an image requires algorithmic improvements, workload partitioning, or an appropriate background-processing design. Async/await is especially valuable for using threads efficiently during I/O waits.

The asynchronous request flow

The ASP.NET Core request pipeline is an asynchronous chain of middleware, endpoint execution, and result processing. Even if a controller action is asynchronous, a synchronous database call inside the service or repository can still block a thread. Adding async only to the controller is therefore not enough.

  1. The controller calls the service with await.
  2. The service awaits an asynchronous repository or DbContext API.
  3. The repository passes the received CancellationToken to the data-access method.
  4. Each layer returns a Task or Task<T> to its caller.

Incorrect implementation: synchronous blocking

In the following example, the controller calls an asynchronous service method but blocks by using .Result:

[HttpGet("{id:int}")]
public ActionResult<ProductDto> Get(int id)
{
    var product = _productService.GetByIdAsync(id).Result;

    if (product is null)
        return NotFound();

    return Ok(product);
}

This code may appear to work in light testing. Under load, however, every request occupies a ThreadPool thread while waiting for the database response. As concurrent traffic increases, queued work grows, additional threads are created, and response times become worse. .Wait() and GetAwaiter().GetResult() belong to the same family of synchronous waiting problems.

Classic UI-style deadlocks do not occur in every modern ASP.NET Core scenario, but that does not make synchronous blocking safe or efficient. The fundamental problem is that a thread is unnecessarily held while the application waits for an asynchronous operation to finish.

Correct implementation: await across the layers

DTO and repository

public sealed record ProductDto(int Id, string Name, decimal Price);

public interface IProductRepository
{
    Task<ProductDto?> FindAsync(
        int id,
        CancellationToken cancellationToken = default);
}

public sealed class ProductRepository : IProductRepository
{
    private readonly AppDbContext _db;

    public ProductRepository(AppDbContext db)
    {
        _db = db;
    }

    public Task<ProductDto?> FindAsync(
        int id,
        CancellationToken cancellationToken = default)
    {
        return _db.Products
            .AsNoTracking()
            .Where(p => p.Id == id)
            .Select(p => new ProductDto(p.Id, p.Name, p.Price))
            .SingleOrDefaultAsync(cancellationToken);
    }
}

The repository returns Task<ProductDto?> directly. Since no additional asynchronous transformation is required, avoiding an unnecessary async/await layer is valid here. Passing the token to SingleOrDefaultAsync allows the database provider to cancel the query when cancellation is supported. AsNoTracking and projection are included only to avoid unnecessary tracking and column loading; they are not the main subject of this lesson.

Service layer

public interface IProductService
{
    Task<ProductDto?> GetByIdAsync(
        int id,
        CancellationToken cancellationToken = default);
}

public sealed class ProductService : IProductService
{
    private readonly IProductRepository _repository;

    public ProductService(IProductRepository repository)
    {
        _repository = repository;
    }

    public async Task<ProductDto?> GetByIdAsync(
        int id,
        CancellationToken cancellationToken = default)
    {
        var product = await _repository.FindAsync(id, cancellationToken);

        return product;
    }
}

The service layer may later contain authorization checks, business rules, or composition of multiple data sources. Keeping the token in the method signature prevents cancellation from being lost. If the service performs no transformation, it could also return the repository task directly; in this example, await keeps the method ready for future business logic and easy to read.

Controller layer

[ApiController]
[Route("api/products")]
public sealed class ProductsController : ControllerBase
{
    private readonly IProductService _service;

    public ProductsController(IProductService service)
    {
        _service = service;
    }

    [HttpGet("{id:int}")]
    public async Task<ActionResult<ProductDto>> GetById(
        int id,
        CancellationToken cancellationToken)
    {
        var product = await _service.GetByIdAsync(
            id,
            cancellationToken);

        if (product is null)
            return NotFound();

        return Ok(product);
    }
}

ASP.NET Core can bind an action parameter of type CancellationToken to the request lifetime. If the client disconnects or the server cancels the request, the token can become signaled. Defining the token in the action is not enough by itself; it must also be passed through the service, repository, and external resource calls.

Stopping unnecessary work with CancellationToken

If a client disconnects during a long-running operation, continuing to spend resources on a result that will no longer be consumed is wasteful. The following example passes the same token to both a database query and an HTTP call:

public async Task<OrderDetailsDto?> GetDetailsAsync(
    int orderId,
    CancellationToken cancellationToken)
{
    var order = await _db.Orders
        .AsNoTracking()
        .Where(o => o.Id == orderId)
        .Select(o => new OrderDetailsDto(o.Id, o.CustomerId))
        .SingleOrDefaultAsync(cancellationToken);

    if (order is null)
        return null;

    var shipping = await _httpClient.GetFromJsonAsync<ShippingDto>(
        $"shipping/{order.Id}",
        cancellationToken);

    return order with { Shipping = shipping };
}

Cancellation should not automatically be treated as an application failure. ASP.NET Core and supporting libraries may throw OperationCanceledException when an operation is canceled. Converting that exception to a 500 response in every controller is usually incorrect. When a client has abandoned the request, the response may no longer matter. If a custom operation needs an explicit cancellation check, use cancellationToken.ThrowIfCancellationRequested() at appropriate boundaries.

Why async void should not be used

Do not use async void for HTTP actions or application services. An async void method does not return a task that the caller can await. ASP.NET Core may consider the request complete too early, while error handling, testing, and response lifetime management become unreliable. HTTP actions should return Task<IActionResult>, Task<ActionResult<T>>, or another suitable Task type.

Measuring the performance effect

Do not validate an async/await change only through code review. Measure both versions with the same data, machine, and comparable load profile. For example, create two diagnostic endpoints:

  • /api/diagnostics/products-blocking: an incorrect version that uses .Result.
  • /api/diagnostics/products-async: a correct version using end-to-end await and CancellationToken.

During testing, observe total requests, concurrent requests, average and p95/p99 latency, error rate, ThreadPool thread count, and queue length. A single average can hide the severe delays experienced by a small number of requests waiting in a queue.

Run both endpoints for the same duration and concurrency, regardless of the load-testing tool you choose. Use dotnet-counters to observe runtime counters, dotnet-stack to inspect thread stacks, and, when necessary, dotnet-trace to investigate wait events. If the blocking implementation causes ThreadPool thread count and request latency to rise while CPU usage remains relatively low, synchronous blocking is a strong suspect.

MeasurementExpected trend in the incorrect versionExpected trend in the correct version
p95 latencyRises quickly as load increasesRemains more stable
ThreadPool thread countMay grow unnecessarilyMay remain lower and steadier
CPU usageCan remain lower than expected because threads are blockedResources can be used more efficiently
Work after cancellationMay continue unnecessarilyCan stop in supporting layers

Actual results depend on hardware, database behavior, network latency, and the load profile. The table is not a guarantee; it is a guide to the behaviors worth investigating.

Common mistakes

  • Making only the controller asynchronous: The problem remains if the service or repository still uses synchronous APIs.
  • Fire-and-forget async calls: Calling _service.RefreshAsync(); without awaiting it loses error and lifetime control.
  • Dropping the token between layers: The database or HTTP call may continue even after the controller knows that the request was canceled.
  • Wrapping everything in Task.Run: Wrapping an I/O-bound operation in Task.Run does not make server-side I/O more efficient and can add scheduling overhead.
  • Changing async code without measurement: Lower average latency for one endpoint does not prove that ThreadPool behavior improves under load.
  • Reporting cancellation as a generic failure: An abandoned client request should be observed without creating misleading application-error alerts.

Short practice exercise

  1. Create a simple ProductsController, ProductService, and repository.
  2. Use a database query or a controlled asynchronous delay to represent a slow data operation.
  3. Write an incorrect endpoint that uses .Result.
  4. Convert the second endpoint and all layers to task-based asynchronous methods and propagate CancellationToken.
  5. Test both endpoints under the same load and record p95 latency, error rate, and ThreadPool counters.
  6. Disconnect the client early and verify, through logs or a test double, that the token reaches the repository.

Conclusion

Correct async/await usage in ASP.NET Core is more than adding async to an action method. The entire call chain—from controller to service, repository, database, or HTTP client—should follow an asynchronous design. Synchronous waits such as .Result and .Wait() can contribute to ThreadPool starvation and increasing latency under load. CancellationToken reduces wasted work when the client no longer needs the result.

The next optimization step will examine data access in more detail. However, without a sound asynchronous foundation, techniques such as query optimization, caching, or response compression cannot deliver their full scalability benefits.

Sources