Search code examples
c#taskcancellation-token

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.


Solution

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

    token.Register(() => { /*...*/ });