Chapter 10. Cancellation

The .NET 4.0 framework introduced exhaustive and well-designed cancellation support. This support is cooperative, which means that cancellation can be requested but not enforced on code. Since cancellation is cooperative, it isn’t possible to cancel code unless it is written to support cancellation. For this reason, I recommend supporting cancellation in as much of your own code as possible.

Cancellation is a type of signal, with two different sides: a source that triggers the cancellation and a receiver that then responds to the cancellation. In .NET, the source is CancellationTokenSource and the receiver is CancellationToken. The recipes in this chapter cover both sources and receivers of cancellation in normal usage and describe how to use the cancellation support to interoperate with nonstandard forms of cancellation.

Cancellation is treated as a special kind of error. The convention is that canceled code will throw an exception of type OperationCanceledException (or a derived type, such as TaskCanceledException). This way the calling code knows that the cancellation was observed.

To indicate to calling code that your method supports cancellation, you should take a CancellationToken as a parameter. This parameter is usually the last parameter, unless your method also reports progress (Recipe 2.3). You can also consider providing an overload or default parameter value for consumers that do not require cancellation:

public void CancelableMethodWithOverload ...

Get Concurrency in C# Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.