Cancellation Tokens in C# Asynchronous Programming
Quick Answer
Cancellation Tokens in C# provide a standardized way to cancel asynchronous operations cooperatively. They allow tasks to be cancelled safely and efficiently, improving responsiveness and resource management in asynchronous programming.
Learning Objectives
- Explain the purpose of Cancellation Tokens in a practical learning context.
- Identify the main ideas, terms, and decisions involved in Cancellation Tokens.
- Apply Cancellation Tokens in a simple real-world scenario or practice task.
Introduction
Asynchronous programming in C# allows applications to remain responsive by running tasks in the background. However, sometimes these tasks need to be cancelled before completion.
Cancellation Tokens provide a cooperative mechanism to cancel asynchronous operations safely and efficiently.
Cancellation tokens enable graceful task cancellation without abrupt termination.
What are Cancellation Tokens?
Cancellation Tokens are objects used to signal cancellation requests to asynchronous or long-running operations.
They allow tasks to check periodically if cancellation has been requested and respond accordingly.
- Implemented via the CancellationToken struct.
- Controlled by a CancellationTokenSource.
- Supports cooperative cancellation between caller and callee.
How to Use Cancellation Tokens
To use cancellation tokens, you create a CancellationTokenSource and pass its token to the asynchronous method.
Inside the method, you check the token's IsCancellationRequested property or call ThrowIfCancellationRequested to handle cancellation.
- Create a CancellationTokenSource instance.
- Pass CancellationToken to async methods.
- Check token status periodically within the task.
- Handle OperationCanceledException if thrown.
Example: Cancelling a Task
The following example demonstrates creating a cancellable task and cancelling it after a delay.
Best Practices for Cancellation Tokens
Proper use of cancellation tokens improves application responsiveness and resource management.
- Always pass CancellationToken to async methods that support cancellation.
- Check for cancellation frequently in long-running loops or operations.
- Handle OperationCanceledException to clean up resources.
- Avoid ignoring cancellation requests to prevent wasted work.
- Use linked tokens to combine multiple cancellation sources if needed.
Common Mistakes When Using Cancellation Tokens
Misusing cancellation tokens can lead to unresponsive applications or resource leaks.
- Not checking the token inside the task, causing cancellation to be ignored.
- Swallowing OperationCanceledException without proper handling.
- Creating CancellationTokenSource but never cancelling it.
- Passing default CancellationToken which never cancels.
- Not disposing CancellationTokenSource when done.
Practical Example
This example runs a task that prints iterations every 500ms. The task checks for cancellation and throws if requested. After 2 seconds, the cancellation is triggered, and the task stops gracefully.
Examples
using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
var cts = new CancellationTokenSource();
var task = Task.Run(async () =>
{
for (int i = 0; i < 10; i++)
{
cts.Token.ThrowIfCancellationRequested();
Console.WriteLine($"Iteration {i}");
await Task.Delay(500);
}
}, cts.Token);
// Cancel after 2 seconds
await Task.Delay(2000);
cts.Cancel();
try
{
await task;
}
catch (OperationCanceledException)
{
Console.WriteLine("Task was cancelled.");
}
}
}This example runs a task that prints iterations every 500ms. The task checks for cancellation and throws if requested. After 2 seconds, the cancellation is triggered, and the task stops gracefully.
Best Practices
- Pass CancellationToken to all cancellable async methods.
- Check cancellation frequently in loops or long-running operations.
- Handle OperationCanceledException to clean up resources.
- Dispose CancellationTokenSource after use to free resources.
- Use linked tokens to combine multiple cancellation signals.
Common Mistakes
- Ignoring cancellation requests inside tasks.
- Not handling OperationCanceledException properly.
- Forgetting to cancel the CancellationTokenSource.
- Passing default CancellationToken which never cancels.
- Not disposing CancellationTokenSource leading to resource leaks.
Hands-on Exercise
Implement a Cancellable Countdown
Write an asynchronous method that counts down from 10 to 0 with a delay of 1 second between counts. Use a CancellationToken to allow cancelling the countdown.
Expected output: The countdown prints numbers every second and stops immediately when cancellation is requested.
Hint: Pass a CancellationToken parameter and check for cancellation inside the loop.
Interview Questions
What is a CancellationToken in C# and why is it used?
InterviewA CancellationToken is a struct used to signal cancellation requests to asynchronous or long-running operations. It enables cooperative cancellation, allowing tasks to stop execution gracefully when cancellation is requested.
How do you trigger cancellation of a task using CancellationToken?
InterviewYou trigger cancellation by calling the Cancel method on the CancellationTokenSource that created the token passed to the task. The task then observes the token and cancels accordingly.
What exception is commonly thrown when a cancellation is requested?
InterviewOperationCanceledException is thrown when a task detects a cancellation request and throws to exit the operation gracefully.
MCQ Quiz
1. What is the best first step when learning Cancellation Tokens?
A. Understand the purpose and basic idea
B. Skip directly to advanced implementation
C. Ignore examples and practice
D. Memorize terms without context
Correct answer: A
Starting with the purpose and basic idea makes later examples and practice easier to understand.
2. Which activity helps reinforce Cancellation Tokens?
A. Reading once without practice
B. Building or writing a small practical example
C. Avoiding review questions
D. Skipping the summary
Correct answer: B
A small practical example helps connect the topic to real usage.
3. Which statement is most accurate about this topic?
A. Cancellation Tokens in C# provide a standardized way to cancel asynchronous operations cooperatively.
B. Cancellation Tokens never needs examples
C. Cancellation Tokens is unrelated to practical work
D. Cancellation Tokens should be learned without checking results
Correct answer: A
The correct option is based on the available topic explanation.
Key Takeaways
- Cancellation Tokens in C# provide a standardized way to cancel asynchronous operations cooperatively.
- They allow tasks to be cancelled safely and efficiently, improving responsiveness and resource management in asynchronous programming.
- Asynchronous programming in C# allows applications to remain responsive by running tasks in the background.
- However, sometimes these tasks need to be cancelled before completion.
- Cancellation Tokens provide a cooperative mechanism to cancel asynchronous operations safely and efficiently.
Summary
Cancellation Tokens are essential for managing cancellation in C# asynchronous programming.
They provide a cooperative way for tasks to respond to cancellation requests safely.
Proper use of cancellation tokens improves application responsiveness and resource management.
Frequently Asked Questions
Can CancellationToken cancel any task automatically?
No, CancellationToken does not forcibly stop tasks. Tasks must cooperatively check the token and respond to cancellation requests.
What happens if a task ignores the cancellation token?
If a task ignores the cancellation token, it will continue running until completion, potentially wasting resources.
Is it necessary to dispose CancellationTokenSource?
Yes, disposing CancellationTokenSource releases unmanaged resources and is recommended when the source is no longer needed.
What is Cancellation Tokens?
Cancellation Tokens in C# provide a standardized way to cancel asynchronous operations cooperatively.
Why is Cancellation Tokens important?
They allow tasks to be cancelled safely and efficiently, improving responsiveness and resource management in asynchronous programming.
How should I practice Cancellation Tokens?
Asynchronous programming in C# allows applications to remain responsive by running tasks in the background.

