在网上搜索了大约4个小时后,我仍然无法理解Windows Phone 7上的异步功能。我试图运行该代码,但看起来我的webClient事件“DownloadStringCompleted”从未引发过。我试着在这里等待答案,但它只是冻结我的应用程序。任何人都可以帮助解释为什么它不起作用?
internal string HTTPGet()
{
string data = null;
bool exit = false;
WebClient webClient = new WebClient();
webClient.UseDefaultCredentials = true;
webClient.DownloadStringCompleted += (sender, e) =>
{
if (e.Error == null)
{
data = e.Result;
exit = true;
}
};
webClient.DownloadStringAsync(new Uri(site, UriKind.Absolute));
//while (!exit)
// Thread.Sleep(1000);
return data;
}
确定。发现了什么! http://blogs.msdn.com/b/kevinash/archive/2012/02/21/async-ctp-task-based-asynchronous-programming-for-windows-phone.aspx 好极了! :)
答案 0 :(得分:3)
它不是模拟器的问题。您希望从HttpGet()方法返回数据,但是在发生webClient的实际响应之前,数据已经返回(为空)。因此我建议你对代码进行一些修改并尝试。
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(new Uri(site, UriKind.Absolute));
然后在DownloadCompleted事件处理程序(或回调)中,您可以实现实际结果
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var response= e.Result; // Response obtained from the site
}