Skip to main content
 首页 » 编程设计

c#之多线程应用程序中第 4 个 HttpWebRequest 异常超时

2024年02月02日28落叶无声

我有一个充当服务器的多线程控制台应用程序。每次新客户端连接到 TcpListener 时,服务器都会生成一个新线程:

//code copied from http://www.switchonthecode.com/tutorials/csharp-tutorial-simple-  threaded-tcp-server 
//blocks until a client has connected to the server 
TcpClient client = tcpListener.AcceptTcpClient();   
//create a thread to handle communication with connected client 
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm)); 
                clientThread.Start(client); 

该线程使用以下代码发出多个 HttpWebRequests:

public static HttpWebResponse HttpGet(string pRequestURI, string pArgs) 
{ 
    string requestURI = string.Format("{0}?{1}", pRequestURI, pArgs); 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURI); 
    request.Method = "GET"; 
    request.ContentType = "application/x-www-form-urlencoded"; 
    HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
    return response; 
} 

问题是,我在 FOURTH REQUEST 上超时。这真的很奇怪,我无法掌握它。该代码在单线程应用程序中工作得很好。我还确保使用以下方法关闭响应流:

response.Close(); 

requestURI 是正确的,因为我尝试将它复制并粘贴到我的浏览器中。实际上,无论第 4 个请求是什么(我尝试过不同的请求),我总是会超时。

我猜可能是线程限制的问题,但是我真的不知道怎么解决。任何建议将不胜感激。

谢谢。

请您参考如下方法:

经过大量的血汗和泪水,我设法解决了它。

这真的是一个愚蠢的错误,原来有一个地方我没有关闭请求。

由于某些(未知)原因,这不会影响从 Web 应用程序发出的请求,但是,当从控制台应用程序发出请求时,会遇到超时问题。

感谢@arx 的帮助 - 非常感谢。