5

System.Net.WebClient().DownloadString(url)結果を待っている間にUIをフリーズせずにメソッドを呼び出すためのチュートリアルやサンプルコードを提供してもらえますか?

これはスレッドで行う必要があると思いますか?オーバーヘッド コードをあまり使わずに使用できる簡単な実装はありますか?

ありがとう!


DownloadStringAsync を実装しましたが、UI はまだフリーズしています。何か案は?

    public void remoteFetch()
    {
            WebClient client = new WebClient();

            // Specify that the DownloadStringCallback2 method gets called
            // when the download completes.
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(remoteFetchCallback);
            client.DownloadStringAsync(new Uri("http://www.google.com"));
    }

    public void remoteFetchCallback(Object sender, DownloadStringCompletedEventArgs e)
    {
        // If the request was not canceled and did not throw
        // an exception, display the resource.
        if (!e.Cancelled && e.Error == null)
        {
            string result = (string)e.Result;

            MessageBox.Show(result);

        }
    }
4

2 に答える 2

2

WebClient.DownloadStringAsync()メソッドを確認してください。これにより、UI スレッドをブロックすることなく非同期でリクエストを行うことができます。

var wc = new WebClient();
wc.DownloadStringCompleted += (s, e) => Console.WriteLine(e.Result);
wc.DownloadStringAsync(new Uri("http://example.com/"));

(また、完了したら WebClient オブジェクトを Dispose() することを忘れないでください)

于 2011-05-25T02:10:46.780 に答える
1

あなたはBackgroundWorkerを使うか、@FulstowがDownStringAsynchメソッドを言ったように使うことができます。

Backgorundワーカーに関するチュートリアルは次のとおりです:http://www.dotnetperls.com/backgroundworker

于 2011-05-25T02:23:21.010 に答える