2010-09-30 28 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