HttpWebResponse get stuck while running in a loop

荒凉一梦 提交于 2020-02-14 09:21:16

问题


I build this method (c#) in order to receive the HTTP response status code from an URL. whene I run this method ones it's works fine, but when I run it in a loop, the third time its stuck. any clue??

 public static string isAlive(string url)
    {
        Console.WriteLine("start: Is Alive Test");
        WebRequest request = WebRequest.Create(url);
        try
        {
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            return Convert.ToString((int)response.StatusCode);
        }
        catch(WebException ex)
        {
            HttpWebResponse res  = (HttpWebResponse)ex.Response;
            return Convert.ToString((int)res.StatusCode);
        }
    }

the loop

        for (int i = 0; i < 5; i++)
        {
            string a = isAlive("https://www.yahoo.com/");
            Console.WriteLine(a);
        }

回答1:


You're not calling Dispose on the HttpWebResponse object, which means that the connection is still lying around. If you change your code to the following:

public static string isAlive(string url)
{
   Console.WriteLine("start: Is Alive Test");
   WebRequest request = WebRequest.Create(url);
   try
   {
       using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            return Convert.ToString((int)response.StatusCode);
        }

   }
   catch(WebException ex)
   {
       using(HttpWebResponse res  = (HttpWebResponse)ex.Response)
       {
          return Convert.ToString((int)res.StatusCode);
       }
   }
}

the using statement will implicitly call Dispose for you, which will close the connection.

The reason your code is halting after the second iteration is because .Net has a built in maximum number of connections it will open to a website, which is by default 2. This is controlled by System.Net.ServicePointManager.DefaultConnectionLimit which you can increase should you need to.




回答2:


It might have to do with you not closing the HttpWebResponse. Add a finally to that try catch which closes the response. Also close the WebException response within the catch.




回答3:


Use "using" and it will work well.

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            return Convert.ToString((int)response.StatusCode);
        }



回答4:


  • You need to wrap HttpWebResponse var into using statement because it's disposable
  • Before checking ex.Response.StatusCode make sure that ex.Status is a ProtocolError
  • And also consider making your method asynchronous for performance considerations
  • Since your method is returning a status code, there might be a better name for it than isAlive

Sample:

public static async Task<string> GetStatusCode(string url)
{
    var request = (HttpWebRequest)WebRequest.Create(url);

    try
    {
        using (var response = (HttpWebResponse)await request.GetResponseAsync())
        {
            return response.StatusCode.ToString();
        }
    }
    catch (WebException ex)
    {
        return ex.Status == WebExceptionStatus.ProtocolError ?
                ((HttpWebResponse)e.Response).StatusCode.ToString() : null;
    }
}


来源:https://stackoverflow.com/questions/21903837/httpwebresponse-get-stuck-while-running-in-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!