Skip to content
Tutorials Center
My learning

Topics

Lesson 99 of 182 ยท Async and Concurrency

Cancellation and Timeouts

Learn cooperative cancellation in C# - CancellationTokenSource, CancellationToken, OperationCanceledException, CancelAfter timeouts, linked tokens and PeriodicTimer.

Sooner or later you need to stop something that is already running: the user closes a dialog, a web request is abandoned, a search is replaced by a newer search, a server shuts down. In .NET there is exactly one standard way to do that, and it is cooperative. Nobody forcibly kills your code; instead, the caller hands the work a token, the work checks the token at convenient points, and when the token says "stop", the work cleans up and ends.

Two types make up the system. A CancellationTokenSource is the control: it is held by whoever may cancel. A CancellationToken is a small read-only struct handed to the work. Every serious async API in .NET accepts a token, usually as the last parameter. This lesson shows how to cancel, how to write cancellable methods, how to react to cancellation, how to set timeouts, how to combine tokens, and how to run a repeating job with PeriodicTimer. It builds on tasks, async/await and task combinators.

The basic pattern

Create a source, pass its Token to the work, and call Cancel() when you want it to stop. The work calls token.ThrowIfCancellationRequested() (or passes the token on to another API that does).

C# Cancelling a loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

When the loop reaches 5 the work cancels its own source (normally another part of the program does that, such as a button handler). On the next iteration ThrowIfCancellationRequested throws an OperationCanceledException, the task ends as Canceled (not Faulted) and the await rethrows the exception. The check happens only where you call it. A loop that never looks at the token can never be cancelled; that is what "cooperative" means.

Passing the token down

You rarely write loops that poll tokens by hand. Almost every async .NET method takes a token and stops promptly for you.

C# Task.Delay observes the token

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Task.Delay returns a cancelled task immediately when the token fires, so we do not wait the ten seconds. (The exception type is TaskCanceledException, a subclass of OperationCanceledException; catching the base class handles both.) The convention for your own methods: accept a CancellationToken cancellationToken = default parameter, pass it to every call that takes one, and call ThrowIfCancellationRequested() in long CPU loops.

Name the parameter cancellationToken (or token) and make it the last parameter. default means "never cancelled", so callers who do not care can leave it out.

Handling cancellation

Cancellation is normal, not an error. The typical rules:

  • Catch OperationCanceledException at the place that started the work, where you know why it was cancelled, and treat it as a quiet outcome (no error log, no failure message).
  • Do not catch it in the middle and swallow it, or the caller will think the work finished normally.
  • Use finally or using for cleanup so resources are released when cancellation unwinds the stack.
  • Prefer when (cancellationToken.IsCancellationRequested) filters if you must distinguish your own cancellation from a timeout inside another library.
C# Cleanup with finally when cancelled

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Items 1 to 3 are processed (cancellation is requested during item 3, and the check happens at the top of the next iteration), the finally block runs, and the caller sees the cancellation. Notice how the cancellation point decides how much extra work happens: check often enough that a stop request is honored quickly.

Timeouts with CancelAfter

A timeout is just a cancellation triggered by a clock. CancelAfter (or the constructor that takes a TimeSpan) schedules Cancel() for you.

C# CancelAfter as a timeout

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The when filter checks that our source fired, which distinguishes a timeout from some other cancellation. On older code you will see CancellationTokenSource timeouts built from Task.WhenAny(work, Task.Delay(...)); the token approach is better because the work actually stops instead of continuing in the background.

Linking tokens

Often an operation should stop for any of several reasons: the caller cancelled, a timeout elapsed, the application is shutting down. CancellationTokenSource.CreateLinkedTokenSource combines tokens into one.

C# A linked token: timeout or caller cancel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first call is only stopped by the 100 ms timeout. The second starts with an already-cancelled caller token, so the linked token is cancelled at once. Checking the original tokens afterwards tells you why it stopped. Always dispose linked sources (using), because they register callbacks on the parent tokens.

Reacting to cancellation with Register

Some work is not a loop and cannot poll, for example a blocking call into a library. token.Register(callback) runs a callback when the token is cancelled. Combine it with TaskCompletionSource to make cancellable wrappers.

C# Register runs a callback on cancel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Dispose the registration when it is no longer needed. CancellationToken.None (the same as default) is a token that can never be cancelled, which lets APIs skip all the machinery.

Repeating work with PeriodicTimer

For "do this every N seconds" jobs (polling, heartbeats, cache refresh), PeriodicTimer gives a clean async loop. WaitForNextTickAsync waits for the next tick and returns false when the timer is disposed; passing a token makes the wait cancellable.

C# PeriodicTimer with a cancellation token

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Unlike while (true) { await Task.Delay(...); }, the timer keeps a steady rhythm and does not drift by the time your body takes. If the body runs longer than the period, ticks do not pile up: at most one pending tick is remembered. This pattern is the heart of a worker in the generic host.

Pitfalls

  • Forgetting to pass the token. Accepting a token but not forwarding it to inner calls makes cancellation silently ineffective.
  • Not disposing the source. A CancellationTokenSource with a timer or linked registrations should be disposed.
  • Swallowing OperationCanceledException in the middle of a call chain.
  • Cancelling expecting an instant stop. Cancellation takes effect only at the next check; blocking calls that ignore tokens keep running.
  • Using cancellation for errors. A failure is an exception; cancellation is a request by the caller.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which object do you hold if you want to be able to cancel?

    The source controls cancellation (Cancel, CancelAfter); the token is the read-only handle given to the work.
  2. 2. What does ThrowIfCancellationRequested() do when cancellation has been requested?

    It throws OperationCanceledException, and a task that ends that way is Canceled, not Faulted.
  3. 3. Why is cancellation called cooperative?

    If the work never observes the token, cancellation has no effect.
  4. 4. How do you build a token that fires when a caller cancels or after 2 seconds, whichever comes first?

    A linked source is cancelled when any of the source tokens is cancelled.
  5. 5. What does await timer.WaitForNextTickAsync(token) do when the token is cancelled while waiting?

    The wait is cancellable and ends with OperationCanceledException; it returns false only when the timer is disposed.

Summary

  • Cancellation is cooperative: a CancellationTokenSource owns the signal, a CancellationToken carries it to the work, and the work stops at its next check.
  • Accept a CancellationToken as the last parameter, forward it to every call, and use ThrowIfCancellationRequested() in long loops.
  • Cancelled tasks end Canceled and throw OperationCanceledException; treat it as a normal outcome, catch it where you started the work, and clean up in finally.
  • CancelAfter creates timeouts; CreateLinkedTokenSource merges several reasons to stop; Register runs a callback on cancel.
  • PeriodicTimer runs repeating async work with a steady rhythm and stops with a token.

Next: Parallel and PLINQ