문제

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.

도움이 되었습니까?

해결책

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

token.Register(() => { /*...*/ });
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top