2012-06-25 83 views
0

在网上搜索大约4小时后,我仍然不明白Windows Phone 7上的异步函数。我试图运行该代码,但它看起来像我的webClient的事件“DownloadStringCompleted”从未被提出。我试图在这里等待一个答案,但它只是冻结我的应用程序。任何人都可以帮忙解释为什么它不起作用?Windows Phone 7.1 HTTP GET与DownloadStringAsync

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 耶! :)

回答

3

它不是模拟器的问题。你想从你的HttpGet()方法中返回数据,但是在来自webClient的实际响应发生之前,数据已经被返回(为空)。因此我建议您对代码进行一些更改并尝试。

WebClient client = new WebClient(); 
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted); 
client.DownloadStringAsync(new Uri(site, UriKind.Absolute)); 

然后在DownloadCompleted事件处理程序(或回调),您manupulate实际结果

void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
{ 
    var response= e.Result; // Response obtained from the site 
} 
+0

因此,有没有什么办法让在同一方法性反应? – Hazardius

+1

这是Async的事情,你不能确定它什么时候完成下载。所以它只是在该事件处理程序完成时返回。 – Cheesebaron

+0

我接受了。感谢帮助。 – Hazardius

相关问题