Cancellation tokens in C# are used to signal that a task or operation should be cancelled. They allow for the cooperative cancellation of a task or operation, rather than aborting it forcibly.
Cancellation tokens in C# are used to signal that a task or operation should be cancelled. They allow for the cooperative cancellation of a task or operation, rather than aborting it forcibly.
There are two main ways to check if a cancellation token has been cancelled:
- The
IsCancellationRequested
property - The
ThrowIfCancellationRequested
method
The IsCancellationRequested Property
The IsCancellationRequested property of the CancellationToken class is a Boolean value that indicates whether the associated cancellation token has been cancelled. It is set to true when the cancellation token is cancelled using the Cancel method of the CancellationTokenSource class, and is set to false when the cancellation token has not been cancelled or has been reset.
Here is an example of how the IsCancellationRequested property can be used in a task:
using System.Threading;
namespace CancellationTokensExample
{
class Program
{
static void Main(string[] args)
{
// Create a cancellation token source
var cts = new CancellationTokenSource();
// Create a cancellation token from the source
var token = cts.Token;
// Start a task that will complete after a delay
var task = Task.Factory.StartNew(() =>
{
for (int i = 0; i < 100; i++)
{
// Check if the task has been cancelled
if (token.IsCancellationRequested)
{
// End the task
Console.WriteLine("Task cancelled");
return;
}
// Perform some work
Console.WriteLine("Task running");
Thread.Sleep(200);
}
// Task completed
Console.WriteLine("Task completed");
}, token);
// Wait for a key press
Console.ReadKey();
// Cancel the task
cts.Cancel();
// Wait for the task to complete
task.Wait(token);
}
}
}
In this example, a task is started using the Task.Factory.StartNew method and a cancellation token is passed as an argument. The task loops through a loop 100 times, performing some work and delaying for 200 milliseconds on each iteration.
Inside the loop, the task checks the IsCancellationRequested property of the cancellation token. If this property is true, it means that the cancellation token has been cancelled and the task should end. If the property is false, the task continues running.
After the task is started, the program waits for a key press from the user. When the user presses a key, the CancellationTokenSource object's Cancel method is called, which cancels the associated cancellation token and sets the IsCancellationRequested property to true. The task ends and a message is printed to the console.
The ThrowIfCancellationRequested Method
The ThrowIfCancellationRequested method of the CancellationToken class throws an OperationCanceledException if the cancellation token has been cancelled. This can be useful if you want to cancel a task or operation and throw an exception if it is cancelled.
Here is an example of how the ThrowIfCancellationRequested method can be used in a task:
using System;
using System.Threading;
namespace CancellationTokensExample
{
class Program
{
static void Main(string[] args)
{
// Create a cancellation token source
var cts = new CancellationTokenSource();
// Create a cancellation token from the source
var token = cts.Token;
// Start a task that will complete after a delay
var task = Task.Factory.StartNew(() =>
{
for (int i = 0; i < 100; i++)
{
// Check if the task has been cancelled
token.ThrowIfCancellationRequested();
// Perform some work
Console.WriteLine("Task running");
Thread.Sleep(200);
}
// Task completed
Console.WriteLine("Task completed");
}, token);
// Wait for a key press
Console.ReadKey();
// Cancel the task
cts.Cancel();
try
{
// Wait for the task to complete
task.Wait(token);
}
catch (OperationCanceledException)
{
// Task was cancelled
Console.WriteLine("Task cancelled");
}
catch (Exception ex)
{
// Handle other exceptions
}
}
}
}
In this example, a task is started using the Task.Factory.StartNew method and a cancellation token is passed as an argument. The task loops through a loop 100 times, performing some work and delaying for 200 milliseconds on each iteration.
Inside the loop, the task calls the ThrowIfCancellationRequested method of the cancellation token. If the cancellation token has been cancelled, this method throws an OperationCanceledException.
After the task is started, the program waits for a key press from the user. When the user presses a key, the CancellationTokenSource object's Cancel method is called, which cancels the associated cancellation token. The task ends and an OperationCanceledException is thrown. The program catches the exception and prints a message to the console.
Nice article! Please don't forget that
CancellationTokenSource
implementsIDisposable
so don't forget to use theusing
keyword eg.:using var cts = new CancellationTokenSource();