为什么WebRequest始终在第一个请求上超时,但从不在任何后续请求上超时

Rah*_*hly 7 .net c# webrequest httpwebrequest

遇到问题,WebRequest.GetResponse()第一次通话时呼叫挂起并超时,但在第一次通话后,一切正常.

        try {
            WebRequest myHttpWebRequest = WebRequest.Create(@"http://192.168.x.x/");
            // Sends the HttpWebRequest and waits for the response.         
            myHttpWebRequest.Timeout = 1000;
            WebResponse myHttpWebResponse = myHttpWebRequest.GetResponse();
        } catch(Exception e) {
            Console.WriteLine("Failure 1");
        }
        try {
            WebRequest myHttpWebRequest = WebRequest.Create(@"http://192.168.x.x/");
            // Sends the HttpWebRequest and waits for the response.         
            myHttpWebRequest.Timeout = 1000;
            WebResponse myHttpWebResponse = myHttpWebRequest.GetResponse(); 
        } catch(Exception e) {
            Console.WriteLine("Failure 2");
        }
        try {
            WebRequest myHttpWebRequest = WebRequest.Create(@"http://192.168.x.x/");
            // Sends the HttpWebRequest and waits for the response.         
            myHttpWebRequest.Timeout = 1000;
            WebResponse myHttpWebResponse = myHttpWebRequest.GetResponse(); 
        } catch(Exception e) {
            Console.WriteLine("Failure 3");
        }
Run Code Online (Sandbox Code Playgroud)

在控制台应用程序中使用此代码,我总是收到一个Failure 1.是否在调试器下运行.我做了一个1000循环,它总是在第一个失败,从来没有任何其他.实际上,在读取Web服务器的日志时,它实际上从未收到第一个请求.我在这里错过了什么吗?

Jon*_*eet 9

编辑:我已经意识到下面的答案符合完全相反的情况,第一个请求有效但其他人没有.但是,它仍然很重要 - 你真的应该处理你的回答.如果在报告错误时也会报告异常消息,这也很有用...

要弄清楚这里发生了什么,你应该真正使用像WireShark这样的东西,这样你就可以看出问题是在做出请求但是没有响应,或者是否甚至没有做出.

我想知道问题是否实际上是它正在解析一个代理,或类似的东西......而且在第二个请求超时之前,有足够的时间来解决它.尝试增加超时.同样,这应该通过WireShark可见.


您没有处理Web响应,因此第二个请求的连接池将等待重新获得该连接.

将该WebResponse部分放在一个using声明中,您可能会发现它一切正常:

using (WebResponse myHttpWebResponse = myHttpWebRequest.GetResponse())
{
}
Run Code Online (Sandbox Code Playgroud)

这是假设你真正一些与响应,当然.否则你可以写:

myHttpWebRequest.GetResponse().Dispose();
Run Code Online (Sandbox Code Playgroud)

:)