Understanding CancellationToken in .NET 9.0

In .NET 9.0, working with async and parallel code is common — but not every task should keep running forever. Sometimes, you need to stop a process safely, like when a user cancels an action or a request takes too long. That’s where the CancellationToken helps.

CancellationToken

A CancellationToken is a signal used to tell running code that it should stop. It works together with a CancellationTokenSource , which sends the stop signal. You pass the token to tasks or async methods, and they can check whether a cancellation has been requested and then stop their work properly.

We usually use a CancellationToken in these cases:

  • Tasks that run for a long time or have loops.

  • I/O operations such as API calls or database queries.

  • Background services or hosted worker processes.

  • Parallel tasks using Parallel.ForEachAsync .

Using cancellation tokens helps stop tasks safely instead of suddenly ending them, which prevents leaving work unfinished or data in a bad state.

Example

  
    // See https://aka.ms/new-console-template for more information
Console.WriteLine("--------Cancellation Token----------!");

using var cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(3));

try
{
    await DoWorkAsync(cts.Token);
}
catch (OperationCanceledException)
{
    Console.WriteLine("Operation cancelled.");
}

Console.WriteLine("--------End of Cancellation Token Example----------!");
Console.ReadLine();
static async Task DoWorkAsync(CancellationToken token)
{
    for (int i = 0; i < 10; i++)
    {
        token.ThrowIfCancellationRequested();
        Console.WriteLine($"Processing {i + 1}");
        await Task.Delay(1000, token);
    }
}
  

Explanation (Courtesy: GitHub Copilot 😉):

  1. The program writes a start marker and creates a CancellationTokenSource ( cts ) that will automatically cancel after 3 seconds via cts.CancelAfter(...) .

  2. 2.It calls DoWorkAsync(cts.Token) inside a try so that cancellation can be observed and handled.

  3. 3. DoWorkAsync loops up to 10 times, calling the token.ThrowIfCancellationRequested() , printing the progress, and awaiting Task.Delay(1000, token) - either the explicit check or the delayed task will observe cancellation.

  4. When the token is cancelled, an OperationCanceledException is thrown and caught, the program prints "Operation cancelled.", then prints the end marker and waits for input.

Output

CancellationToken_01

Conclusion

The CancellationToken in .NET 9.0 offers a safe and clean way to stop async tasks without killing threads abruptly. It helps your app respond faster, use fewer resources, and stay stable even under heavy load — making it an important feature for modern, high-performance .NET applications.

Happy Coding!