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");s
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 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()) //When connection is lost it stays stuck kere
{
if (reader.TokenType == JsonToken.StartObject)
{
JObject obj = JObject.Load(reader);// Load each object from the stream and do something with it
Dispatcher.BeginInvoke((Action)(() => { debugOutput(obj["closeoutBid"].ToString()); }));
}
ct.ThrowIfCancellationRequested();
}
}, ct);
}
}
}
catch (HttpRequestException ex)
{
MessageBox.Show("Error. " + ex.Message);
}
catch (OperationCanceledException)
{
MessageBox.Show("Your submission was canceled.");
}
}
I have thit "while" loop and it constantly reads a Json stream. But when the connection is lost there is no way to get out of the "while" loop. It remains stuck in the "reader.Read()" line, waiting for next Json token, which will never arriver because the connection is lost. So no code in the while loop will be executed. Can somebody help me please? Thank you.