问候,
我正在尝试使用以下代码下载网页:
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循环正在旋转,但是result的值从未更新。控制台是一个TextBox。对可能发生的事情有任何想法吗?
谢谢,
调频
最佳答案
我看不到代码中循环的目的以及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,您将获得页面源-它是恒定的并且不会改变(与动态提要不同),因此您不需要在那里的循环。