我创建了一个 Windows Phone 8.1项目,我试图在按钮上运行 async
方法,然后等待方法完成,但是方法从来没有完成过。这是我的代码:
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;
}
它会挂在 task.Wait()
上。
我改变了我的按钮点击方法为 async
和使用 await
之前的 async
方法,我得到的结果(await GetResponse<string>("url")
)。Task<List<string>> task = GetResponse<string>("url")
怎么了?
我做错了什么?
谢谢你的帮助!