Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run code when a CancellationToken is cancelled?

Given a CancellationToken, I want to call a 'cancel' method on an object that represents an asynchronous operation when the CancellationToken is cancelled. Is this possible?

Background: I'm interfacing with an API that represents an async op the following way (more or less):

class AsyncOp
{
    void Start(Action callback);//returns 'immediately', while beginning an async op. Callback is called when the operation completes.
    void Cancel();//aborts async operation and calls callback
}

I can wrap this in a method Task DoAsyncOp() easily enough, but I want to support cancellation, eg Task DoAsyncOp(CancellationToken cancellationToken). In my case, when the CancellationToken is cancelled, call Cancel on the AsyncOp object.

like image 402
mackenir Avatar asked May 07 '14 12:05

mackenir


People also ask

How do you handle a cancellation token?

The wait handle of the cancellation token will become signaled in response to a cancellation request, and the method can use the return value of the WaitAny method to determine whether it was the cancellation token that signaled. The operation can then just exit, or throw an OperationCanceledException, as appropriate.

How does a cancellation token work?

A CancellationToken enables cooperative cancellation between threads, thread pool work items, or Task objects. You create a cancellation token by instantiating a CancellationTokenSource object, which manages cancellation tokens retrieved from its CancellationTokenSource. Token property.

Does disposing a CancellationTokenSource cancel it?

The Dispose method leaves the CancellationTokenSource in an unusable state. After calling Dispose , you must release all references to the CancellationTokenSource so the garbage collector can reclaim the memory that the CancellationTokenSource was occupying.

Which object do you inspect to determine if a long running task will be Cancelled?

The background long-running tasks are cancelled by using the CancellationToken object in Blazor. If an application downloads the data to render in view and then you navigate to another page, the CancellationToken cancels the download by using the cancel() method.


1 Answers

You can register an Action to be invoked when the token is canceled:

token.Register(() => { /*...*/ });
like image 123
Christoph Fink Avatar answered Nov 02 '22 23:11

Christoph Fink