I couldn't find from search anyone having similar issues so:
I'm trying to get XML from server with HttpClient, but my UI freezes weirdly at line "task.Wait()". This is the code:
public void register() {
String data = "register=" + (accountName) + "&email0=" +
(email) + "&email1=" + (otherEmail);
var task = MakeRequest(data);
task.Wait(); //freezes here
var response = task.Result;
String resultstring = response.Content.ReadAsStringAsync().Result;
}
private static async Task<System.Net.Http.HttpResponseMessage> MakeRequest(String data)
{
var content = new StringContent(data, Encoding.UTF8, "application/x-www-form-urlencoded");
var httpClient = new System.Net.Http.HttpClient();
System.Net.Http.HttpResponseMessage responseMessage=null;
try
{
responseMessage = await httpClient.PostAsync(server, content);
}
catch(Exception ex)
{
responseMessage.ReasonPhrase = string.Format("RestHttpClient.SendRequest failed: {0}", ex);
}
return responseMessage;
}
Any help is greatly appreciated!
It's not freezing weirdly at all - it's freezing entirely reasonably.
You're calling task.Wait()
, which stops your UI thread from doing any more work until that task has completed. However, that task itself needs to get back to the UI thread when the task returned by httpClient.PostAsync
completes, in order to continue with the rest of your async method.
Basically, you shouldn't use Task.Wait()
or Task.Result
unless you know for sure that the task itself won't be blocked waiting to continue on the thread you're currently executing on.
Ideally, your register
method (which should be Register
to follow .NET naming conventions) should be asynchronous as well, so you can await the task returned by MakeRequest
.
Additionally, you should probably change the way MakeRequest
awaits the task - as the rest of that method doesn't really need to run on the UI thread, you can use:
responseMessage = await httpClient.PostAsync(server, content).ConfigureAwait(false);
Finally, this line:
responseMessage.ReasonPhrase = string.Format("RestHttpClient.SendRequest failed: {0}", ex);
... will throw a NullReferenceException
if it ever executes. If an exception is thrown, responseMessage
will still be null.
See more on this question at Stackoverflow