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/"));

(另外,完成后不要忘记 Dispose() WebClient 对象)

于 2011-05-25T02:10:46.780 回答
1

您可以使用 BackgroundWorker 或 @Fulstow 所说的 DownStringAsynch 方法。

这是关于 Backgorund worker 的教程:http: //www.dotnetperls.com/backgroundworker

于 2011-05-25T02:23:21.010 回答