Module 1 · Task lifetimes and cooperative cancellation · Lesson 1 of 7
Own the task: async completion, exceptions and cancellation
The endpoint returned success. Its refresh failed later. Who should see that failure?
An inventory refresh required by the response needs an owner that awaits it. Work that must survive the request needs a recoverable job contract. Start by predicting the first two lines of the complete program below, then check what a canceled token actually changes.
A complete program: prefix, fault, cancel, ignore
Before running, predict when the prefix prints, whether the released refresh returns a result, and whether the final canceled token prevents success.
This .NET console example uses explicit signals instead of delays to establish the important ordering. Copy the code into Program.cs in a .NET 10 console project. The output below follows from the control flow.
using System;
using System.Threading;
using System.Threading.Tasks;
public static class Program
{
public static async Task Main()
{
var releaseRefresh = new TaskCompletionSource<bool>(
TaskCreationOptions.RunContinuationsAsynchronously);
Task<int> refresh = RefreshAsync(releaseRefresh.Task);
Console.WriteLine($"returned to caller, completed {refresh.IsCompleted}");
releaseRefresh.SetResult(true);
Console.WriteLine($"awaited result {await refresh}");
// The fault is established explicitly, not inferred after a sleep.
Task failing = Task.FromException(
new InvalidOperationException("inventory refresh failed"));
Console.WriteLine($"before observation: IsFaulted {failing.IsFaulted}");
try { await failing; }
catch (InvalidOperationException ex)
{
Console.WriteLine($"observed by await: {ex.Message}");
}
using var cts = new CancellationTokenSource();
var entered = new TaskCompletionSource<bool>(
TaskCreationOptions.RunContinuationsAsynchronously);
Task waiting = WaitForCancellationAsync(entered, cts.Token);
await entered.Task; // Establish entry before requesting cancellation.
cts.Cancel();
try { await waiting; }
catch (OperationCanceledException)
{
Console.WriteLine($"canceled: status {waiting.Status}");
}
using var ignored = new CancellationTokenSource();
ignored.Cancel();
Console.WriteLine($"ignoring work finished: {await IgnoresTokenAsync(ignored.Token)}");
}
static async Task<int> RefreshAsync(Task release)
{
Console.WriteLine("synchronous prefix runs");
await release;
return 42;
}
static async Task WaitForCancellationAsync(
TaskCompletionSource<bool> entered, CancellationToken token)
{
entered.SetResult(true);
await Task.Delay(Timeout.Infinite, token);
}
static Task<string> IgnoresTokenAsync(CancellationToken token)
=> Task.FromResult("yes, token was never checked");
}Expected output, by inspection:
synchronous prefix runs returned to caller, completed False awaited result 42 before observation: IsFaulted True observed by await: inventory refresh failed canceled: status Canceled ignoring work finished: yes, token was never checked
What each part establishes:
- The prefix prints before control returns. The release task is still incomplete when IsCompleted is read, so no scheduler-speed assumption is needed. Releasing it lets RefreshAsync finish.
- Task.FromException creates an already-faulted task. Checking IsFaulted does not observe its exception; awaiting it does. This is not a demonstration that a garbage-collection event will fire.
- The entry signal establishes that the worker has started. Whether cancellation reaches Task.Delay before or after its registration, the canceled token makes the wait end in cancellation. Main still awaits the worker before disposing the source.
- A method may return a Task without the async keyword. The final method never observes the canceled token, so it returns successfully. No work is automatically interrupted by passing a token.
RunContinuationsAsynchronously avoids running registered continuations inline in the signal-completion call; it does not promise a dedicated thread. In a test harness, add a bounded hang guard and cleanup that releases or cancels and then joins any started work if an assertion fails.
Check your prediction
The refresh reaches an incomplete await. Which event happens before its caller regains control?
Show answer
Correct answer: A
Calling the async method executes its synchronous prefix before returning at the incomplete await. Task describes completion; neither a new thread nor a commit follows from the call.
Option B: Async does not promise a new thread.
Option C: Execution reaching an await is not a transaction commit.
Option D: Starting a task does not request cancellation.
Hint: Find the first Console.WriteLine in RefreshAsync.
The final helper receives an already-canceled token but never checks it. What does this program print?
Show answer
Correct answer: C
IgnoresTokenAsync returns a successful Task<string>. Passing a token alone does not interrupt code or change that returned task.
Option A: No cancellation check or canceled task is produced.
Option B: The helper does not throw.
Option D: A canceled token can be passed normally.
Hint: Read the implementation rather than the parameter name.
Task describes completion
A Task represents completion, not necessarily a new thread. Awaiting I/O lets the caller yield while the operation is incomplete; it does not make CPU work free. Keep asynchronous call chains asynchronous. Blocking with Result or Wait can consume worker threads and, in some synchronization contexts, deadlock.
An async method normally executes synchronously until it reaches an incomplete await. Therefore creating many tasks can still perform substantial synchronous work before control returns. Use Task.Run for a deliberate CPU scheduling decision, not as a wrapper around every network call.
Choose an owner
For work required to produce the response, await it within the request. For work that must survive the request, persist a job in a durable system and return an accepted/job-status contract. An unawaited task inside a controller is not a durable job queue.
Use async Task for asynchronous methods whose completion matters. Reserve async void for event-handler signatures that require it; its caller cannot await completion through a Task.
Cancellation is a request
The initiator owns a CancellationTokenSource; downstream operations normally receive only its token. Cancellation is cooperative. Passing a token does not stop code that ignores it, and cancellation does not roll back a database commit.
Illustrative method body:
static async Task<int> CountAsync(CancellationToken token)
{
int completed = 0;
for (int i = 0; i < 5; i++)
{
token.ThrowIfCancellationRequested();
await Task.Delay(20, token);
completed++;
}
return completed;
}This sample needs System.Threading and System.Threading.Tasks, supplied by implicit usings in a standard modern console project. The delay models cancellable work; it is not a recommended test synchronization technique.
Three final states and how they reach you
A task ends in one of three states:
- RanToCompletion: await returns the result.
- Faulted: the task stores the exception, and await rethrows it. Blocking with Result or Wait wraps it in an AggregateException instead.
- Canceled: the task was marked canceled, for example when an async Task method propagates OperationCanceledException. Such a method does not require that exception to carry a particular token. Await throws OperationCanceledException (TaskCanceledException is a subclass).
The difference matters to callers. A retry policy should not treat a caller-requested cancellation like a dependency failure, and a log that turns every cancellation into an error makes normal client disconnects look like an incident.
By default, an unobserved faulted Task does not terminate a modern .NET process. This is not a guarantee for async void failures, explicit fail-fast calls, or application handlers that terminate the process. The exception sits in the task, and the TaskScheduler.UnobservedTaskException event may report it later, when the task is garbage collected. That is the inventory-refresh defect: the failure exists but nobody owns it. "It did not crash" is not evidence that it worked.
Owning a task in practice
Use this checklist before writing _ = SomethingAsync(); or storing a task in a field:
| Question | Healthy answer |
|---|---|
| Who awaits it? | The request, or a named owner such as a hosted service that tracks it |
| Where does its failure go? | Logged and handled by that owner, with the operation's identity |
| What stops it? | A token from the owner, honored inside the work |
| What survives a restart? | Nothing, unless the job is persisted (queue, outbox or job table) |
| What does the caller learn? | A result, or an accepted response with a job id or status URL |
If the honest answer to "who awaits it?" is "nobody", the work is not owned. For an inventory refresh that the response depends on, await it in the request and pass the request's token. For a refresh that may run later, write a durable job record (or a message) in the same transaction as the change that requires it, and let a background worker own the retries.
Disposing the CancellationTokenSource
The owner that creates a CancellationTokenSource disposes it, after the work and any registrations that use its token have finished. A using var cts in the method that awaits the work is the simplest correct shape, as in the program. Disposing a source does not cancel it, and cancelling it does not dispose it. A source configured with CancelAfter may hold a timer, which is another reason to dispose it promptly.
Interview checkpoint
Explain the lifetime of the work, who awaits it, how failure is observed and what cancellation means after a side effect. A strong answer names these boundaries before choosing an API.
Try a change before reading the check
- Replace the body of
IgnoresTokenAsyncwithTask.FromCanceled<string>(token). Predict the final outcome, then run it. Why does the existingMainnow end differently? - Repair that caller so it deliberately handles cancellation and still observes every task it starts.
- An order was committed before the browser disconnected. Sketch a result lookup using a stable operation ID; say which side effect the token cannot undo.
Compare your reasoning
The replacement returns a canceled task, so its await throws rather than printing the successful string. The existing final await has no cancellation catch; handling the earlier waiting task does not handle a different task. The repair must observe the replacement's outcome at its own call site. A committed order remains durable even if the response is lost: lookup or an idempotency contract helps the caller discover the outcome.
Quick reference
- Start a task only when you can name its owner, who awaits it and where its failure goes.
- Code before the first incomplete await runs on the caller's thread.
- await returns the result, rethrows the stored exception, or throws OperationCanceledException.
- Result and Wait block a thread and wrap failures in AggregateException; keep the chain async.
- An unawaited faulted task fails silently; it does not prove success.
- Cancellation is cooperative: pass the token on and check it, or nothing stops.
- The creator of a CancellationTokenSource disposes it after the dependent work ends.
- Cancellation never rolls back a committed side effect; design an idempotency key or a status lookup.
- Work that must outlive the request needs a durable job, not a background task in a controller.
TechInterviewNotes Editorial Team · Updated 27 Oct 2026 ·