我正在使用此代码段与取消令牌执行异步查询:
var _client = new HttpClient( /* some setthngs */ );
_client.GetAsync(someUrl, cancellationToken).ContinueWith(gettingTask => {
cancellationToken.ThrowIfCancellationRequested();
SomeStuffToDO();
}, TaskScheduler.FromCurrentSynchronizationContext());
}, TaskScheduler.FromCurrentSynchronizationContext());
但是,当取消操作时,cancellationToken.ThrowIfCancellationRequested();
会抛出异常。我知道这条线应该是这个东西。但是,在开发环境中,例外导致视觉工作室休息。我怎么能避免这个?
答案 0 :(得分: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包装该调用(或等待其包含方法的位置)。