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.
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.
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.
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.
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.
You can register an Action
to be invoked when the token is canceled:
token.Register(() => { /*...*/ });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With