2010-09-30 33 views
1

我有一個叫做GetIP的函數,我在啓動時以及用戶按下按鈕時調用它。由於某種原因,它不會在啓動時崩潰,但它在使用按鈕調用函數時會發生。沒有任何東西只是凍結。對於功能Webclient.DownloadString崩潰

代碼:

 private void GetIP() 
     { 
     string pageTitle = functions.GetWebPageTitle("http://xyro18.woelmuis.nl/index.php"); 
     string[] ip = new string[2]; 
     ip = pageTitle.Split('|'); 
     currentIpLabel.Text = ip[0]; 
     webIpLabel.Text = ip[1]; 
     } 

現在,我發現它就在我的getWebPageTitle功能崩潰的功能

代碼:

public static string GetWebPageTitle(string url) 
    { 
     // Create a request to the url 
     HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest; 
     request.Method = "HEAD"; 
     // If the request wasn't an HTTP request (like a file), ignore it 
     if (request == null) return null; 

     // Use the user's credentials 
     request.UseDefaultCredentials = true; 

     // Obtain a response from the server, if there was an error, return nothing 
     HttpWebResponse response = null; 
     try { response = request.GetResponse() as HttpWebResponse; } 
     catch (WebException) { return null; } 

     // Regular expression for an HTML title 
     string regex = @"(?<=<title.*>)([\s\S]*)(?=</title>)"; 

     // If the correct HTML header exists for HTML text, continue 
     if (new List<string>(response.Headers.AllKeys).Contains("Content-Type")) 
      if (response.Headers["Content-Type"].StartsWith("text/html")) 
      { 
       // Download the page 
       WebClient web = new WebClient(); 
       web.UseDefaultCredentials = true; 
       string page = web.DownloadString(url); 

       // Extract the title 
       Regex ex = new Regex(regex, RegexOptions.IgnoreCase); 
       return ex.Match(page).Value.Trim(); 
      } 

     // Not a valid HTML page 
     return null; 
    } 

它崩潰的web.DownloadString

與崩潰我的意思是凍結,並不顯示任何豁免等

回答

0

好了,我不能說我知道爲什麼它凍結,但這裏有一些建議,可以幫助:

  • 呼叫response.Close()當你用它做(例如當你從方法返回時)。
  • WebClient類實現了IDisposable,所以您應該嘗試使用構造。
  • 而不是每次爲單個匹配創建一個新的正則表達式對象,請使用Regex類中的靜態方法。
  • 嘗試將web.Proxy屬性設置爲null,以確保它不會嘗試檢測代理(如默認情況下那樣)。
+0

感謝它的工作,實現了所有的選項,似乎是我沒有關閉響應信號。 – Xyro 2010-09-30 12:09:20