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

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

查看WebClient.DownloadStringAsync()方法,这将允许您异步地发出请求,而不会阻止UI线程。

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

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

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

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