c# - 取消 token 抛出异常。无法捕获OperationCanceledException。我遇到了用户未处理的情况

标签 c# unhandled-exception cancellation cancellation-token

我正在尝试使用取消 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.");
    }
}

最佳答案

我相信您看到“用户未处理的异常”,因为您正在调试器中运行它。要么:

  • 点击继续继续执行代码,或者
  • 在没有调试器的情况下运行代码。

这两个选项都将允许 OperationCanceledExceptioncatch block 捕获。

关于c# - 取消 token 抛出异常。无法捕获OperationCanceledException。我遇到了用户未处理的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60155072/

相关文章:

c# - Angular Material AutoComplete 不加载选项 MVC

c# - 传递给委托(delegate)时作为引用类型处理的整数

c# - XXX.exe 中发生类型为 'System.ExecutionEngineException' 的未处理异常

c# - 该进程无法访问该文件,因为该文件正在被另一个进程使用

c# - 在递归方法中使用 async/await 的正确方法是什么?

c# - 构造函数执行前的属性初始化

ruby - Ruby 中未处理的异常

c# - AggregateException 中的 TaskCanceledException 不包含堆栈跟踪

c# - Task.Wait 在 OperationCanceledException 情况下的意外行为

node.js - 有没有办法使用 Microsoft.AspNetCore.NodeServices 停止 Node.js 上的脚本执行?