2011-05-25 50 views
3

嘗試執行downloadStringAsync()以防止UI凍結10秒當下載一個字節的數據。但是,即使下載完成,它也會凍結UI,就像我使用downloadString()一樣。DownloadStringAsync()不會異步下載字符串

這裏是我的代碼:

public void loadHTML() 
    { 
      WebClient client = new WebClient(); 

      // Specify that the DownloadStringCallback2 method gets called 
      // when the download completes. 
      client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(loadHTMLCallback); 
      client.DownloadStringAsync(new Uri("http://www.example.com")); 
      return; 
    } 

    public void loadHTMLCallback(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; 

      // Do cool stuff with result 

     } 
    } 
+0

您正在下載* *數據一個字節,並注意到一個顯著延遲,異步或不?這本身就是一個巨大的問題。那真的是所有的代碼?如果您確定您的互聯網連接無法以1 bps的速度運行,我認爲您還有其他代碼。產生一個新的線程來異步下載東西應該與大約同時下載一個字節的時間相同。在創建和執行新線程之前,「DownloadStringAsync」可能會同步檢查標題,互聯網連接或其他內容,但這是一種猜測。 – Ryan 2011-05-25 02:58:35

+0

添加了'WebRequest.DefaultWebProxy = null;'現在一切正常!看起來,自動代理檢測是延遲的原因。 – Johnny 2011-05-25 03:46:17

+0

「WebRequest.DefaultWebProxy = null;」在哪裏?我無法找到WebRequest Class的屬性「DefaultWebProxy」,@Johnny。 – mxi1 2013-06-05 03:09:42

回答