我构建此方法(c#)以接收来自URL的HTTP响应状态代码。 当我运行这个方法,它的工作正常,但是当我在一个循环中运行它,第三次卡住了。任何线索?HttpWebResponse在循环中运行时卡住
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);
}
}
循环
for (int i = 0; i < 5; i++)
{
string a = isAlive("https://www.yahoo.com/");
Console.WriteLine(a);
}
你确定它卡住,而不仅仅是等待响应?服务器很可能会限制请求,因为它可能检测到可疑活动(在如此短的时间内向服务器投掷如此多的请求可能会成为DoS攻击)。鉴于您希望在不阻塞UI线程的情况下发出大量请求,您可能需要考虑改为使用“BeginX”/“EndX”调用。 – James
定义'卡住'。如果你的程序在三次尝试后挂起,可能是雅虎服务器拒绝你的快速连续的https请求。另一种选择是您的操作系统阻止快速连接到相同的地址(内部防洪)。编辑 - 答案是另一种选择,你有太多的连接一次打开。 –
您需要将.GetResponse()封装到'using'语句中,并使您的isAlive方法异步以进行性能考虑。看到我的代码示例如下。 –