LLearnCode
Academy/csharp/Trust boundaries and asynchronous work

advanced · 29 minute study

Cancellation is a request; stale results still need a guard

Stop wasting work after a user leaves a screen and prevent an older search response from replacing a newer one.

Loading progressEvidence grows with practice
Useful preparation · 1 prerequisite

Use this as a map, not a lock. If these ideas are familiar, continue.

First, build a mental model

A CancellationToken communicates that work is no longer wanted. Cooperating operations decide how to observe it. A result-order guard separately decides whether a completed result still belongs to the current request.

  1. Pass the token through methods into cancelable I/O and waits instead of accepting it and ignoring it.
  2. Canceled task-based operations commonly surface OperationCanceledException when awaited; handle expected cancellation separately from a genuine failure.
  3. Cancellation does not undo a committed database write or guarantee that a remote server never received a request.
  4. A monotonically increasing request identity can reject stale results even when a dependency ignores or races with cancellation.
Read the codecsharp · educational example
static async Task<int> LoadAsync(CancellationToken token)
{
    await Task.Delay(1000, token);
    return 42;
}

using var source = new CancellationTokenSource();
source.Cancel();
try
{
    int value = await LoadAsync(source.Token);
    Console.WriteLine(value);
}
catch (OperationCanceledException) when (source.IsCancellationRequested)
{
    Console.WriteLine("cancelled");
}
  1. Request cancellation

    The token is already canceled before LoadAsync is called.

  2. Observe

    Task.Delay observes that token; await propagates cancellation.

  3. Handle

    The filtered cancellation handler runs instead of printing a fabricated result.

Production thinking

Take this beyond the example.

Give requests deadlines, forward cancellation and guard result ownership. In write workflows, cancellation and retries must respect transaction boundaries and operation identity.

Sources and further reading

Your evidence

unseen is a local learning signal, not a credential or proof of production competence.

Explain the mental model, then explicitly acknowledge it. Opening a page is not evidence.

Supported retries can complete this lesson. Independent evidence and delayed review determine the skill stage.

Next lesson · Decode data and release resources at explicit boundaries →