Question

So I'm making a program which pretty much makes bulk HttpWebRequests. In this program, speed is main thing. If I can find ways to increase the HttpWebRequests by even a millisecond, then that's excellent.

Okay so my question is this: I have a method which makes a HttpWebRequest (GET request) to a site, and another method which makes a POST HttpWebRequest to the SAME host (slightly different URL, but same host), which is called AFTER the first method every once in a while.

In my first method (the GET request, let's say Method A), I close the WebResponse after I read the response body. Is it faster to leave this WebResponse open, and then call the POST method (let's say Method B), or should I do it how I do it now, close the WebResponse from method A?

Example code:

public string MethodA()
{
   // Make a HttpWebRequest to a URL like: xxxx.yyyy.com
   WebResponse response = request.GetResponse();
   string x = ReadResponseBody(response);
   response.Close();
   if(x.Contains("something"))
      MethodB();
}

public void MethodB()
{
   // Make a POST HttpWebRequest to a URL like: xxxx.zzzz.com (same host).
   WebResponse response = request.GetResponse();
   response.Close();
}

So, should I leave my code as it is, close the first WebResponse from MethodA(), then call MethodB(), or something else?

Also, could anybody give some more tips on how to improve speed, as it is the most important thing in my program, and I need it to be as fast as possible.

Was it helpful?

Solution

You should absolutely close the WebResponse - ideally with a using statement:

using (WebResponse response = request.GetResponse())
{
    string x = ReadResponseBody(response);
}

If you don't close the response, the framework doesn't know that you're done with it, and won't reuse the connection. If you do close the response, the connection is returned to a pool for that host, and can be reused.

As there's a connection limit per host (which is configurable), failing to close responses can end up with timeouts or deadlocks, as your process waits for the web response to be finalized instead (which will then behave like closing). You really don't want to have to wait for the garbage collector to happen to notice the response you've already finished with :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top