问候,
我正在尝试使用以下代码下载网页:
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
字符串的目的。这是我针对您的问题提供的信息。
以下是最终触发该过程的代码:
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,您将获得页面源 - 它是恒定的并且不会更改(与动态提要不同),因此您不需要那里的循环。
关于c# - WebClient.DownloadStringAsync 不适用于 WP7 模拟器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5000070/