Search code examples
c#-4.0asynchronousasync-awaitcancellationcancellationtokensource

Error: The operation was canceled


I'm using this code snippet to do an async query with a cancellation token:

var _client = new HttpClient( /* some setthngs */ );

_client.GetAsync(someUrl, cancellationToken).ContinueWith(gettingTask => {
    cancellationToken.ThrowIfCancellationRequested();
    SomeStuffToDO();
    }, TaskScheduler.FromCurrentSynchronizationContext());
}, TaskScheduler.FromCurrentSynchronizationContext());

But, when operation get cancelled, cancellationToken.ThrowIfCancellationRequested(); throws an exception. I know that this line should to this stuff. But, in developing environment, the exception causes the visual studio to a break. How can I avoid this?


Solution

  • You need to handle within the lambda, like this:

    var _client = new HttpClient( /* some setthngs */ );
    
    _client.GetAsync(someUrl, cancellationToken).ContinueWith(gettingTask => {
        try {
         cancellationToken.ThrowIfCancellationRequested();
         SomeStuffToDO();
        }
        catch (...) { ... }
        finaly { ... }
        }, TaskScheduler.FromCurrentSynchronizationContext());
    }, TaskScheduler.FromCurrentSynchronizationContext());
    

    But _client.GetAsync(someUrl, cancellationToken) might also throw cancellation exception, so you need to wrap that call (or where its containing method is awaited) with a try-catch.