I created Windows Phone 8.1 project and I am trying to run async
method GetResponse<T>(string url)
on button click and waiting for the method to finish, but method is never finishing. Here is my code:
private void Button_Click(object sender, RoutedEventArgs
{
Task<List<MyObject>> task = GetResponse<MyObject>("my url");
task.Wait();
var items = task.Result; //break point here
}
public static async Task<List<T>> GetResponse<T>(string url)
{
List<T> items = null;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
try
{
Stream stream = response.GetResponseStream();
StreamReader strReader = new StreamReader(stream);
string text = strReader.ReadToEnd();
items = JsonConvert.DeserializeObject<List<T>>(text);
}
catch (WebException)
{
throw;
}
return items;
}
It will hang on task.Wait()
.
I changed my button click method to async
and used await
before the async
method and I get the result(await GetResponse<string>("url")
). What is wrong with Task<List<string>> task = GetResponse<string>("url")
?
What am I doing wrong?
Thanks for the help!
async
methods are suffixed withAsync
, i.e. your method name would beGetResponseAsync
. – Gorgoneiontask.Wait();
is redundant here.task.Result
will already calltask.Wait()
when necessary. – Conceivable