2011-05-25 79 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

相關問題