错误:该操作被取消 [英] Error: The operation was canceled

查看:516
本文介绍了错误:该操作被取消的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这个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.

这篇关于错误:该操作被取消的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆