Diana M00nshine
Diana M00nshine

Reputation: 135

Cancellation Token throws exception. Not able to catch OperationCanceledException. I got User-Unhandled

I am trying to cancel an HttpClient stream using a cancellation token but I am not able to handle the "OperationCanceledException". It gives me "User-Unhandled Exception". The same structure was working well in another project in the past. Or is there a better way to cancel the HttpClient stream? Thank you. Here is my code:

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.");
    }
}

Upvotes: 2

Views: 974

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456457

I believe you're seeing "User-Unhandled Exception" because you're running it in the debugger. Either:

  • Click Continue to continue executing the code, or
  • Run the code without the debugger.

Either of these options will allow the OperationCanceledException to be caught by the catch block.

Upvotes: 2

Related Questions