Using HttpWebRequest, Keep-alive not working for m

2019-06-09 03:41发布

问题:

I'm using HttpWebRequest to send many sync requests to the same HTTP URL on localhost, and I need to re-use TCP connections to prevent ephemeral port depletion.

But I don't seem to be able to get Keep-alive working.

Here's my code where I make the HTTP request:

var request = (HttpWebRequest) WebRequest.Create(url);
HttpWebResponse response = null;

request.Method = "GET";
request.KeepAlive = true;

try
{
    response = (HttpWebResponse) request.GetResponse();
    // ...
}
catch (Exception e)
{
    // ...
}
finally
{
    if (response != null)
    {
        response.Close();
    }
}

I call the above code many times in a loop. All requests are successful, and return OK status code (200), but running netstat -ano reveals that there are MANY MANY connections in the TIME_WAIT state, where I expect it to re-use a single connection.

I tried calling both an IIS Express server on localhost (default ASP.NET MVC application) and a WebLogic application, with the same result.

I also tried HttpClient from .NET 4.5.

This quickly results in running out of ephemeral ports.

Is there anything wrong with what I'm doing? How can I make .NET re-use TCP connections?

回答1:

Try response.Dispose(); instead of response.Close();