2011-05-25 82 views
5

有人可以指点我的教程或提供一些示例代码来调用System.Net.WebClient().DownloadString(url)方法,而不会在等待结果时冻结UI吗?如何在不阻止用户界面的情况下使用WebClient?

我认为这需要用线程来完成?有没有一个简单的实现,我可以使用没有太多的开销代码?

谢谢!


已实施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

退房的WebClient.DownloadStringAsync()方法,这会让你做出异步请求,不会阻塞UI线程。

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

(另外,不要忘记的Dispose()WebClient的对象时,你就完蛋了)

+0

嗯...我实现了这个,它仍然冻结UI。这是我的代码:[粘贴在原始帖子上方] – Johnny 2011-05-25 02:29:28

相关问题