3

我正在使用此代码片段执行带有取消令牌的异步查询:

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

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

但是,当操作被取消时,cancellationToken.ThrowIfCancellationRequested();会引发异常。我知道这条线应该是这个东西。但是,在开发环境中,异常会导致视觉工作室中断。我怎样才能避免这种情况?

4

1 回答 1

1

您需要在 lambda 中处理,如下所示:

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)也可能引发取消异常,因此您需要使用 try-catch 包装该调用(或等待其包含方法的位置)。

于 2013-06-13T11:25:15.123 回答