【问题标题】:WebClient.DownloadStringAsync not working with WP7 emulatorWebClient.DownloadStringAsync 不适用于 WP7 模拟器
【发布时间】:2011-06-27 08:52:45
【问题描述】:

您好,

我正在尝试使用以下代码下载网页:

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 的值从未被更新。控制台是一个文本框。对可能发生的事情有什么想法吗?

谢谢,

调频

【问题讨论】:

    标签: c# windows-phone-7 webclient webclient-download


    【解决方案1】:

    我看不到代码中循环的目的,以及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 您将获得页面源 - 它是恒定的并且不会更改(与动态提要不同),因此您不需要那里的循环。

    【讨论】:

    • 感谢您的回复。这很好用,是我见过的最简单的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-02
    • 2017-08-17
    • 1970-01-01
    • 2013-07-05
    • 2011-06-17
    • 2015-06-04
    相关资源
    最近更新 更多