如何在不阻止UI的情况下使用WebClient?

时间:2011-05-25 02:07:19

标签: c# multithreading webclient downloadstring

有人可以指点我一个教程或提供一些示例代码来调用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);

        }
    }

2 个答案:

答案 0 :(得分: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对象)

答案 1 :(得分:1)

您可以使用BackgroundWorker或@Fulstow表示DownStringAsynch方法。

这是关于Backgorund工作人员的教程:http://www.dotnetperls.com/backgroundworker