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

CancellationToken

A CancellationToken is a stop button you can pass to a long job, like a friend who can wave a flag to say 'please stop'. The job checks it and ends politely.

In this page:

  1. CancellationToken
Syntax
csharp
using var cts = new CancellationTokenSource();
cts.CancelAfter(milliseconds);   // or cts.Cancel();

await Task.Delay(milliseconds, cts.Token);   // throws OperationCanceledException

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");
        }
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Never passing the token to inner calls, so cancellation has no effect.
  2. Not checking IsCancellationRequested in long loops.
  3. Forgetting to catch OperationCanceledException.
🔒

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.