2012-06-25 84 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

相關問題