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;
    }

Ok。何かを見つけた! 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 に答える