0

在网上搜索了大约 4 个小时后,我仍然不了解 Windows Phone 7 上的异步函数。我尝试运行该代码,但看起来我的 webClient 的“DownloadStringCompleted”事件从未引发过。我试图在这里等待答案,但它只是冻结了我的应用程序。任何人都可以帮助并解释为什么它不起作用?

    internal string HTTPGet()
    {
        string data = null;
        bool exit = false;
        WebClient webClient = new WebClient();
        webClient.UseDefaultCredentials = true;

        webClient.DownloadStringCompleted += (sender, e) =>
        {
            if (e.Error == null)
            {
                data = e.Result;
                exit = true;
            }
        };

        webClient.DownloadStringAsync(new Uri(site, UriKind.Absolute));

        //while (!exit)
        //    Thread.Sleep(1000);

        return data;
    }

行。发现了一些东西! http://blogs.msdn.com/b/kevinash/archive/2012/02/21/async-ctp-task-based-asynchronous-programming-for-windows-phone.aspx 耶!:)

4

1 回答 1

3

它不是模拟器的问题。您想从 HttpGet() 方法返回数据,但在 webClient 的实际响应发生之前,数据已经返回(为 null)。因此,我建议您对代码进行一些更改并尝试。

WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(new Uri(site, UriKind.Absolute));

然后在 DownloadCompleted 事件处理程序(或回调)中,您操纵实际结果

void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    var response= e.Result; // Response obtained from the site
}
于 2012-06-25T11:58:40.513 回答