> For the complete documentation index, see [llms.txt](https://framework.aic.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://framework.aic.io/technical-guidelines-code-standards-and-tech-stack/c-code-standards/async-await-and-cancellation.md).

# 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

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

## Service Example

```csharp
public async Task<CaseResponse?> GetCaseAsync(
    Guid caseId,
    CancellationToken cancellationToken)
{
    return await _dbContext.Cases
        .AsNoTracking()
        .Where(x => x.Id == caseId)
        .Select(x => new CaseResponse(x.Id, x.Reference, x.Status))
        .SingleOrDefaultAsync(cancellationToken);
}
```

## WPF and MAUI

UI applications must keep the UI thread responsive:

```csharp
public async Task LoadAsync(CancellationToken cancellationToken)
{
    IsBusy = true;

    try
    {
        Cases = await _caseService.GetCasesAsync(cancellationToken);
    }
    finally
    {
        IsBusy = false;
    }
}
```

## 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.
