Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpWebResponse get stuck while running in a loop

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);
        }
like image 357
SIE-Coder Avatar asked Dec 20 '22 18:12

SIE-Coder


1 Answers

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.

like image 103
Ceilingfish Avatar answered Jan 03 '23 04:01

Ceilingfish