Error: The operation was canceled

吃可爱长大的小学妹 提交于 2019-12-24 14:03:59

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/17082827/error-the-operation-was-canceled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!