views:

585

answers:

4

The question says it all,

I have some code like, this code is used very heavily:

      using (HttpWebResponse response = _GetHttpWebResponse(requestURIString, msgBody, methodType, contentType, headers)) {
   //*** do something with it...
   //*** Call response.Close() ???
  }

The code works fine today, but the connections to the server stay open for quite some time. (checked using TCPView)

Is there a benefit to calling the Close method? is it recommended, or maybe recommended not to do it, and why?

+6  A: 

When Dispose() is called on WebResponse (HttpWebReponse's base class), it calls it's Close() method for you. A quick glance using Reflector confirms this.

Edit (in response to comment): If it's called for you already, why call it explicitly? For the sake of clarity? I think if people understand the using (X x = ...) statement, they'll understand that it is closing the underlying connection. You gain nothing by calling it explicitly in this case.

Sean Bright
I know it does, the question is if I should call .Close anyway
BlackTigerX
you're right, "using" calls the Dispose, GC calls the Finalize
BlackTigerX
Cool, glad to hear it. Sorry it wasn't the right answer for ya.
Sean Bright
can't accept two answers as correct, so I gave you a thumbs up, and accepted the other one
BlackTigerX
A: 

I believe Close is the method that implements IDisposable.Dispose, therefore there is definitely no need to call the Close method beforehand. It is fully redundant.

Noldorin
+2  A: 

The using keyword is a syntactic sugar for try/finally block, which wraps around your HttpWebResponse, since it implements IDisposable. When in the finally clause, it will call the Dispose() method, which will call Close(). This means that you don't have to explicitly call the Close() method.

hmemcpy
A: 

If you have significant code inside the using after you have finished consuming the response then sure calling close is ok. However you might want to consider refactoring your code so that code that doesn't need the response isn't inside the using block.

That said closeing the response doesn't necessarily close the connection. The HTTP/1.1 protocol makes provision for the connection to remain open to make subsequent requests quicker.

AnthonyWJones