我正在尝试使用取消令牌来取消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.");
}
}
我相信您会看到“用户未处理的异常”,因为您正在调试器中运行它。要么:
Continue
继续执行代码,或这两个选项中的任何一个都将使OperationCanceledException
被catch
块捕获。