For the complete documentation index, see llms.txt. This page is also available as Markdown.

Async Await and Cancellation

Purpose

Correct asynchronous programming protects scalability, responsiveness and reliability.

Mandatory Rules

  • Use async APIs for I/O-bound operations.

  • Pass CancellationToken through application, infrastructure and API layers.

  • Do not block on async code using .Result, .Wait() or .GetAwaiter().GetResult().

  • Do not use async void except UI event handlers.

  • Configure timeouts for external calls.

  • Avoid fire-and-forget work unless it is explicitly supervised.

API Example

app.MapPost("/v1/cases", async (
    CreateCaseRequest request,
    ICreateCaseHandler handler,
    CancellationToken cancellationToken) =>
{
    var result = await handler.HandleAsync(request, cancellationToken);
    return result.ToHttpResult();
});

Service Example

WPF and MAUI

UI applications must keep the UI thread responsive:

Cancellation Rules

  • API endpoints receive request-aborted cancellation tokens.

  • Application services accept cancellation tokens.

  • EF Core calls pass cancellation tokens.

  • HTTP calls pass cancellation tokens.

  • Background workers honour stopping tokens.

Fire-and-Forget Rule

Fire-and-forget work must be replaced by:

  • background queue

  • durable message

  • hosted service

  • job scheduler

  • transactional outbox

If fire-and-forget is unavoidable, errors must be logged and the lifetime must be supervised.

Was this helpful?