我使用这个code段做一个取消标记一个异步查询:
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());但是,当运行被取消, cancellationToken.ThrowIfCancellationRequested(); 抛出异常。我知道,这条线应该到这个东西。但是,在开发环境中,异常导致Visual Studio中休息。我怎样才能避免这种情况?
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?
推荐答案您需要将拉姆达内处理,就像这样:
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());但 _client.GetAsync(someUrl,的CancellationToken)也有可能抛出异常注销,所以你需要用的电话(或在其包含的方法等待)与一试-catch。
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.
更多推荐
错误:该操作被取消
发布评论