我正在尝试使用取消 token 取消 HttpClient 流,但我无法处理“OperationCanceledException”。它给了我“用户未处理的异常”。同样的结构在过去的另一个项目中运行良好。 或者有更好的方法来取消 HttpClient 流吗? 谢谢。 这是我的代码:
private async void Start_Click(object sender, RoutedEventArgs e)
{
await DeserializeFromStream();
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
cts.Cancel();
}
private async Task DeserializeFromStream()
{
cts = new CancellationTokenSource();
CancellationToken ct = cts.Token;
try
{
using (var client = new HttpClient())
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("APP_VERSION", "1.0.0");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "tokentokentoken");
using (var request = new HttpRequestMessage(HttpMethod.Get, "https://stream-fxpractice.oanda.com/v3/accounts/101-004-4455670-001/pricing/stream?instruments=EUR_USD"))
using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct))
{
var Timeout = TimeSpan.FromMilliseconds(1000);
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode) { Console.WriteLine("\n success!"); } else { Console.WriteLine((int)response.StatusCode); }
var stream = await response.Content.ReadAsStreamAsync();
using (StreamReader sr = new StreamReader(stream))
using (JsonTextReader reader = new JsonTextReader(sr))
{
reader.SupportMultipleContent = true;
await Task.Run(() =>
{
while (reader.Read())
{
if (reader.TokenType == JsonToken.StartObject)
{
// Load each object from the stream and do something with it
JObject obj = JObject.Load(reader);
if (obj["type"].ToString() == "PRICE")
Dispatcher.BeginInvoke((Action)(() => { debugOutput(obj["closeoutBid"].ToString()); }));
}
ct.ThrowIfCancellationRequested();
}
}, ct);
}
}
}
catch (OperationCanceledException) // includes TaskCanceledException
{
MessageBox.Show("Your submission was canceled.");
}
}
最佳答案
我相信您看到“用户未处理的异常”,因为您正在调试器中运行它。要么:
- 点击
继续
继续执行代码,或者 - 在没有调试器的情况下运行代码。
这两个选项都将允许 OperationCanceledException
被 catch
block 捕获。
关于c# - 取消 token 抛出异常。无法捕获OperationCanceledException。我遇到了用户未处理的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60155072/