C# 4.0 错误:操作已取消

C# 4.0 错误:操作已取消,c#-4.0,asynchronous,async-await,cancellation,cancellationtokensource,C# 4.0,Asynchronous,Async Await,Cancellation,Cancellationtokensource,我正在使用此代码段使用取消令牌执行异步查询: var _client = new HttpClient( /* some setthngs */ ); _client.GetAsync(someUrl, cancellationToken).ContinueWith(gettingTask => { cancellationToken.ThrowIfCancellationRequested(); SomeStuffToDO(); }, TaskScheduler

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

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

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

但是,当操作被取消时,
cancellationToken.ThrowIfCancellationRequested()引发异常。我知道这条线应该和这东西联系起来。但是,在开发环境中,异常会导致VisualStudio中断。如何避免这种情况?

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

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

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

但是
\u client.GetAsync(someUrl,cancellationToken)
也可能引发取消异常,因此您需要用try-catch包装该调用(或等待其包含方法的位置)。

您是指VS停止并显示“异常”对话框的“visual studio中断”吗?无论是开发还是运行时,如果您没有处理异常,它将导致您的应用程序失败。您需要捕获并处理异常以避免发生。@G.Stoynev Yes VS停止并显示“异常”对话框。那么,我在哪里可以处理异常呢?在主线程还是异步线程中?