0Pricing
C# Academy · Lesson

CancellationToken patterns; cooperative cancel

Pass and honor CancellationToken: create CTS, poll/throw for cancel, pass to async APIs, and clean up with registrations.

CancellationToken patterns; cooperative cancel is a free C# Academy lesson on CoddyKit — lesson 1 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Cooperative cancellation

Aim: Cancel work cooperatively.

  • Create a CancellationTokenSource
  • Pass CancellationToken down
  • Check IsCancellationRequested or call ThrowIfCancellationRequested()
  • Honor cancel quickly and cleanly

Caller-driven cancel

Create a CancellationTokenSource, pass the token, and cancel from the caller; the callee throws OperationCanceledException.

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

public class Program
{
  static async Task WorkAsync(CancellationToken ct)
  {
    // Poll occasionally; throw to end cooperatively
    for (int i = 0; i < 5; i++)
    {
      ct.ThrowIfCancellationRequested();
      Console.WriteLine("Step " + i);
      await Task.Delay(100, ct); // pass token to async API
    }
  }

  public static void Main(string[] args)
  {
    var cts = new CancellationTokenSource();
    Task t = WorkAsync(cts.Token);

    // Cancel after a short delay (simulated user action)
    Thread.Sleep(180);
    cts.Cancel();

    try
    {
      t.GetAwaiter().GetResult();
    }
    catch (OperationCanceledException)
    {
      Console.WriteLine("Canceled!");
    }
  }
}

Forwarding tokens

Forward the token through every async layer so inner calls can stop promptly.

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

public class Program
{
  static async Task<string> FetchAsync(CancellationToken ct)
  {
    await Task.Delay(80, ct); // pretend I/O
    ct.ThrowIfCancellationRequested();
    return "data";
  }

  static async Task<string> ProcessAsync(CancellationToken ct)
  {
    string raw = await FetchAsync(ct); // forward token
    await Task.Delay(80, ct);
    return raw.ToUpperInvariant();
  }

  public static void Main(string[] args)
  {
    var cts = new CancellationTokenSource();
    Task<string> job = ProcessAsync(cts.Token);
    cts.CancelAfter(100); // schedule a cancellation
    try
    {
      Console.WriteLine(job.GetAwaiter().GetResult());
    }
    catch (OperationCanceledException)
    {
      Console.WriteLine("Pipeline canceled");
    }
  }
}

token.Register cleanup

Use token.Register to attach a small cleanup action that runs when cancellation is requested.

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

public class Program
{
  static async Task UseRegistrationAsync(CancellationToken ct)
  {
    using (ct.Register(() => Console.WriteLine("Cleanup: releasing temp resources")))
    {
      for (int i = 0; i < 3; i++)
      {
        ct.ThrowIfCancellationRequested();
        await Task.Delay(120, ct);
        Console.WriteLine("Tick " + i);
      }
    }
  }

  public static void Main(string[] args)
  {
    var cts = new CancellationTokenSource();
    Task t = UseRegistrationAsync(cts.Token);
    Thread.Sleep(150);
    cts.Cancel();
    try { t.GetAwaiter().GetResult(); }
    catch (OperationCanceledException) { Console.WriteLine("Canceled with cleanup"); }
  }
}

Linked sources

CreateLinkedTokenSource merges multiple signals (e.g., user cancel + timeout) into a single token.

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

public class Program
{
  static async Task WorkAsync(CancellationToken ct)
  {
    await Task.Delay(500, ct);
    Console.WriteLine("Finished work");
  }

  public static void Main(string[] args)
  {
    var parent = new CancellationTokenSource();
    var timeout = new CancellationTokenSource();
    timeout.CancelAfter(200);

    // Link both sources: cancel if parent OR timeout requests
    var linked = CancellationTokenSource.CreateLinkedTokenSource(parent.Token, timeout.Token);

    Task t = WorkAsync(linked.Token);
    try { t.GetAwaiter().GetResult(); }
    catch (OperationCanceledException) { Console.WriteLine("Canceled by parent/timeout"); }
    finally { linked.Dispose(); parent.Dispose(); timeout.Dispose(); }
  }
}

Best practices

Tips:

  • Pass tokens to async APIs (Task.Delay, I/O) so they stop promptly.
  • Throw OperationCanceledException to end work; do not swallow it.
  • Dispose CancellationTokenSource if it owns timers/registrations.
  • Keep handlers fast; do minimal work in Register.

Cooperative cancel rule

Quick check: What is the correct way for a method to respond to a cancellation request?

Recap

Recap: Make cancel cooperative—pass tokens, poll or ThrowIfCancellationRequested, attach small cleanup, and link sources for combined signals.

Frequently asked questions

Is the “CancellationToken patterns; cooperative cancel” lesson free?

Yes — the full text of “CancellationToken patterns; cooperative cancel” is free to read here on the web, and the C# Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.

What will I learn in “CancellationToken patterns; cooperative cancel”?

Pass and honor CancellationToken: create CTS, poll/throw for cancel, pass to async APIs, and clean up with registrations. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “CancellationToken patterns; cooperative cancel” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. CancellationToken patterns; cooperative cancel
  2. Timeouts, IProgress , async disposables (emulation)
  3. Resilience basics: retry & backoff
← Back to C# Academy