I've been stuck on this issue for a few hours now and I can't figure it out for the life of me :(
So I'm using an HttpClient to access an XML file hosted on a web site which i'm utilising in my application.
I've tried CancellationTokens to no avail and can't find any way of debugging this issue further.
My function is as follows:
public static async Task<string> GetXML()
{
string xml = string.Empty;
Uri url = new Uri("http:/blabla.com/CompanyAppsManifest.xml");
HttpClient hCli = new HttpClient();
CancellationTokenSource cts = new CancellationTokenSource(7000);
hCli.DefaultRequestHeaders.TryAppendWithoutValidation("Accept-Encoding", "UTF-8");
hCli.DefaultRequestHeaders.TryAppendWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml, charset=utf-8, text/xml");
try
{
var response = await hCli.GetAsync(url).AsTask(cts.Token);
if (response.IsSuccessStatusCode == true)
{
xml = response.Content.ToString();
hCli.Dispose();
return xml;
}
else
{
hCli.Dispose();
MessageBox.Show("Contact the admin with this info: SC: " + response.StatusCode.ToString() + " Content: " + response.Content.ToString());
if (Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
Debugger.Break();
}
xml = "Operation failed due to: HTTP Failure";
return xml;
}
}
catch (OperationCanceledException)
{
MessageBox.Show("Operation failed to complete in a timely fashion, please ensure you have WiFi active or a stable data connection");
xml = "Operation failed due to timeout";
return xml;
}
catch (Exception ex)
{
MessageBox.Show("error" + ex.Message + " : " + ex.InnerException.Message);
xml = "Operation failed due to exception";
return xml;
}
finally
{
cts = null;
}
}
It's being called from a Method on a public class which has a return type of IEnumerable however it's not flagged as an async method.
The method gets the string from my method in question like so
var ss = GetXML().Result;
Can anyone tell me why
1: The cancellation token isn't functioning as it seems to in all the examples i've been looking at. I can't figure out where i'm going wrong.
and 2. It seems to only freeze the application on the first run, if it freezes when you run it first time and then you close the app and restart it the getAsync method runs fine and the program runs as expected.
Any help or advice will be greatly appreciated as I can't find anything to help me any further :(
Sounds very similar to this issue here: How to debug app hanging on Windows Phone 8.1
I'll provide any extra information required just comment below.
Thanks