← Back to C# Course | Chapter 13: Async Programming | Lesson 5 of 6

CancellationToken

In this page:

  1. CancellationToken

CancellationToken

CancellationToken provides a cooperative way to signal that a running asynchronous operation should stop early. A CancellationTokenSource creates the token and can trigger cancellation with .Cancel(); the running code checks token.IsCancellationRequested or lets an awaited method throw OperationCanceledException. Cancellation is cooperative — the operation must actively check the token to actually stop.

Note: Pass the same CancellationToken down through every awaited call so cancellation propagates properly.

Example: CancellationToken

markup
using System;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        using var cts = new CancellationTokenSource();
        cts.CancelAfter(50);

        try
        {
            await Task.Delay(1000, cts.Token);
            Console.WriteLine("Completed normally");
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("Operation was cancelled");
        }
    }
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.