Question

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

using (HttpWebResponse r = _GetHttpWebResponse(uri, body, method, contentType, headers)) {
    /* do something with the response */

    /* call r.Close() explicitly? */
}

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 explicitly? Is it recommended, or maybe recommended not to do it, and why?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

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.

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