2011-02-15 61 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