2011-02-15 87 views
2

問候工作,WebClient.DownloadStringAsync不是WP7模擬器

我試圖下載一個網頁,用下面的代碼:

public partial class MainPage : PhoneApplicationPage 
{ 
    private static string result = null; 

    // Constructor 
    public MainPage() 
    { 
     InitializeComponent(); 

     LoadFeeds(); 
    } 

    public static void LoadFeedsCompleted(Object sender, DownloadStringCompletedEventArgs e) 
    { 
     result = e.Result; 
    } 

    private void LoadFeeds() 
    { 
     string url = "http://www.cornfedsystems.com"; 
     Uri uri = new Uri(url); 
     WebClient client = new WebClient(); 
     client.DownloadStringCompleted += LoadFeedsCompleted; 
     client.AllowReadStreamBuffering = true; 
     client.DownloadStringAsync(uri); 
     for (; ;) 
     { 
      if (result != null) 
      { 
       console.Text = result; 
       result = null; 
      } 
      Thread.Sleep(100); 
     } 
    } 

} 

此代碼編譯正常,但當我在模擬器啓動,它只是掛在時鐘屏幕上,即等待。我放入了一些斷點,我可以看到for循環正在旋轉,但結果的值永遠不會被更新。控制檯是一個TextBox。有關可能發生什麼的任何想法?

感謝,

FM

回答

4

我看不出你在你的代碼具有循環的目的,以及該result字符串。這是我的問題。

這裏是一個將最終觸發過程的代碼:

string url = "http://www.cornfedsystems.com"; 
Uri uri = new Uri(url); 
WebClient client = new WebClient(); 
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted); 
client.AllowReadStreamBuffering = true; 
client.DownloadStringAsync(uri); 

這裏是事件處理程序:

void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
{ 
    Debug.WriteLine(e.Result); 
} 

所有結果處理應該在將被觸發時,事件處理程序來完成一切都準備好了(在你的情況下 - 字符串被下載)。使用DowhloadStringAsync,您將獲得頁面源代碼 - 它是常量,不會更改(與動態提要不同),因此您不需要那裏的循環。

+0

感謝您的回覆。這工作很好,是我見過的最簡單的代碼。 – 2011-02-15 05:55:30