Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Async and Concurrency

CancellationToken and CancellationTokenSource

Reference for CancellationToken and CancellationTokenSource in C#: cancel tasks, CancelAfter timeouts, linked sources, Register callbacks and best practices.

.NET cancels operations cooperatively. A CancellationTokenSource owns the "cancel" switch, and it hands out CancellationToken values that carry a read-only view of it. The code doing the work receives a token, checks it or passes it on, and stops when the source is cancelled.

Nothing is aborted forcibly. If the worker never looks at the token, cancellation has no effect. Almost every asynchronous .NET API accepts a token as its last parameter, and your own async methods should do the same.

C#
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await DoWorkAsync(cts.Token);

Try it

C# Cancel a loop cooperatively

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.

C# Timeouts, callbacks and linked sources

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.

Syntax

C#
public class CancellationTokenSource : IDisposable
{
    public CancellationTokenSource();
    public CancellationTokenSource(TimeSpan delay);
    public CancellationToken Token { get; }
    public bool IsCancellationRequested { get; }
    public void Cancel();
    public Task CancelAsync();
    public void CancelAfter(TimeSpan delay);
    public bool TryReset();
    public static CancellationTokenSource CreateLinkedTokenSource(params CancellationToken[] tokens);
}

public readonly struct CancellationToken
{
    public bool IsCancellationRequested { get; }
    public bool CanBeCanceled { get; }
    public void ThrowIfCancellationRequested();
    public CancellationTokenRegistration Register(Action callback);
    public static CancellationToken None { get; }
}
Member Description
Cancel() Marks the token cancelled and runs registered callbacks synchronously.
CancelAsync() Runs the callbacks asynchronously (.NET 8+), so the caller is not blocked by slow callbacks.
CancelAfter(delay) Schedules a cancel. Calling it again replaces the earlier schedule.
ThrowIfCancellationRequested() Throws OperationCanceledException if cancelled.
Register(callback) Runs callback on cancel; dispose the returned registration to unregister.
TryReset() Reuses a source that has not been cancelled, if no timer is pending.

Errors: OperationCanceledException signals cancellation; awaiting a canceled task throws TaskCanceledException, which derives from it. Using a disposed source throws ObjectDisposedException. Exceptions from Register callbacks are collected into an AggregateException thrown by Cancel().

Usage notes

  • Pass the token down. Give every async method a CancellationToken cancellationToken = default parameter and forward it to each call you make.
  • Catch OperationCanceledException at the boundary only. Treat it as normal flow, not as an error to log.
  • Dispose the source, especially one with a timer or linked parents; otherwise registrations and timers live longer than needed.
  • Check regularly in CPU loops; a call to ThrowIfCancellationRequested inside the loop body is cheap.
  • Do not cancel from within a lock while callbacks may need the same lock.
  • A token is a struct; copy it freely. A source is a class; share it deliberately.
  • Cancel does not stop the thread. Cleanup in finally still runs, and work already past its last check finishes normally.
  • In ASP.NET Core the HttpContext.RequestAborted token fires when the client disconnects, and minimal API/controller methods can take a CancellationToken parameter directly.