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);
}
HttpWebResponse
var intousing
statement because it's disposableex.Response.StatusCode
make sure that ex.Status is aProtocolError
Sample:
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.
Use "using" and it will work well.
You're not calling
Dispose
on theHttpWebResponse
object, which means that the connection is still lying around. If you change your code to the following: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.