Reputation: 155270
I'm using HttpWebRequest the way that you're meant to: disposing the response when I'm done with it, in the hope that this would make it reuse any available TCP connections, however it doesn't: it closes the connection after the response is received. I see this happening when I use TCPView.
Here's my HttpWebRequest code:
private HttpWebResponse ExecuteRequest(String baseRelativeUri, String method, Ds postValues) {
/////////////////////////////////////////
// Set-up
Uri uri = new Uri( _baseUri, baseRelativeUri );
_cookies.ProcessDomains();
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create( uri );
request.CookieContainer = _cookies;
request.Method = method;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0";
if( postValues != null ) SetPostContent( request, postValues );
/////////////////////////////////////////
// Response
return (HttpWebResponse)request.GetResponse();
}
protected HtmlDocument ExecuteRequestHtml(String baseRelativeUri, String method, Ds postValues, HttpStatusCode expectedStatusCode) {
using(HttpWebResponse response = ExecuteRequest(baseRelativeUri, method, postValues)) {
if( response.StatusCode != expectedStatusCode ) throw new WebException("Did not receive " + expectedStatusCode + " response.");
/////////////////////////////////////////
// HtmlDocument
using(Stream stream = response.GetResponseStream()) {
HtmlDocument doc = new HtmlDocument();
doc.Load( stream );
return doc;
}
}
}
According to MSDN, the HttpWebRequest.KeepAlive property is true by default, as is HttpWebRequest.Pipelines. So what am I doing wrong?
Thanks!
Upvotes: 2
Views: 1347
Reputation: 155270
It turns out I was hitting the "2 simultaneous connections per host" rule that HttpWebRequest respects.
The solution is to set this static property:
System.Net.ServicePointManager.DefaultConnectionLimit = 15;
Sorted :)
Upvotes: 4