Error: The operation was canceled

agent47 picture agent47 · Jun 13, 2013 · Viewed 13.3k times · Source

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?

Answer

G. Stoynev picture G. Stoynev · Jun 13, 2013

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.