Handle cancellation of async method
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Cancellation in async code is cooperative, not magical. The caller signals that work should stop, and the async method must observe that signal, stop at safe points, and clean up correctly. In .NET, that pattern is built around CancellationToken, CancellationTokenSource, and OperationCanceledException.
Accept a CancellationToken
If a method can take noticeable time, let the caller pass a token.
Two important details are happening here:
- the loop checks the token explicitly
- awaited operations also receive the token
That makes cancellation responsive instead of delayed.
Trigger Cancellation from the Caller
The caller usually owns the CancellationTokenSource.
CancelAfter is useful for timeouts, while direct Cancel() is useful for UI buttons or shutdown events.
Propagate the Token Downstream
One of the most common mistakes is accepting a token but not passing it to nested async operations. If your method calls HTTP, database, or file APIs that support cancellation, forward the same token.
If the top-level method is cancelable but inner I/O ignores the token, the cancellation experience will feel broken.
Clean Up Correctly
Cancellation is not an error in the same sense as a bug or infrastructure failure, but cleanup still matters. Use finally blocks for owned resources.
Do not swallow OperationCanceledException silently unless that is the API contract. In many cases, the caller needs to know work did not finish.
Cancellation vs Failure
Keep cancellation distinct from ordinary failure handling:
- cancellation means the caller requested stop
- failure means the operation tried to finish but could not
If you convert cancellation into a generic error, callers lose important control-flow information.
UI and Background-Service Patterns
Typical patterns include:
- cancel button in desktop or mobile UI
- web request aborted by client disconnect
- hosted service shutting down gracefully
- batch job timeout
In all of these, cooperative cancellation is better than forcing a thread or task to stop abruptly.
Linked Tokens for Combined Policies
Sometimes an operation should stop if either the caller cancels or an internal timeout expires. Linked token sources handle that cleanly.
This keeps timeout policy and user-requested cancellation in one cooperative flow.
Common Pitfalls
- Defining a cancelable async method but never accepting a
CancellationToken. - Checking the token once at the start and never again during long work.
- Forgetting to pass the token into awaited operations that support cancellation.
- Swallowing
OperationCanceledExceptionand pretending the work completed normally. - Treating cancellation as a crash instead of expected control flow.
Summary
- Async cancellation in .NET is cooperative and token-driven.
- Methods should accept a
CancellationTokenand observe it during work. - Callers use
CancellationTokenSourceto request stop or apply timeouts. - Propagate the same token into nested async operations.
- Clean up resources and let cancellation remain distinguishable from real failure.
Related reading
- Handle concurrent requests to update the resources
- Handler vs AsyncTask vs Thread
- Handler vs AsyncTask vs Thread
- Handling asynchronous database queries in node.js and mongodb
- Handling Dialogs in WPF with MVVM
- Handling 'Sequence has no elements' Exception
- Handling exceptions from Java ExecutorService tasks
- Handling exceptions from Java ExecutorService tasks

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.