Handling multiple cancellation sources
Background tasks can leverage CancellationTokenSource
to receive cancellation requests from as many sources as necessary. The static CancellationTokenSource.CreateLinkedTokenSource
method accepts an array of CancellationToken
objects to create a new CancellationTokenSource
object that will notify us of cancellation if any of the source tokens receives a request to cancel.
Let’s look at a quick example of how to implement this in our CancellationPatterns project:
- First, open the
PollingExample
class. We are going to create an overload of theCancelWithPolling
method that accepts aCancellationTokenSource
parameter. The two overloads ofCancelWithPolling
will look like this:public static void CancelWithPolling() { using CancellationTokenSource tokenSource = new(); CancelWithPolling(tokenSource); } public static void CancelWithPolling (CancellationTokenSource...