gpt4 book ai didi

c#-4.0 - 错误 : The operation was canceled

转载 作者:行者123 更新时间:2023-12-04 18:09:52 26 4
gpt4 key购买 nike

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

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

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

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

最佳答案

你需要在 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 包装该调用(或等待其包含方法的位置)。

关于c#-4.0 - 错误 : The operation was canceled,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17082827/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com