问题
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 intousing
statement because it's disposable - Before checking
ex.Response.StatusCode
make sure that ex.Status is aProtocolError
- 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