views:

391

answers:

2

I'm getting the response from an HttpWebRequest (using a modified version Jeff Richter's CCR wrappers), then inspecting a few of the headers in order to decide whether or not to continue the download. Sometimes I might not want to continue, so I consequently issue response.Close and request.Abort. Is it necessary to issue GetResponseStream then to close the stream, or is this implicit when one calls response.Close?

After issuing GetResponse, the docs state:

You must call the Close method to close the stream and release the connection. Failure to do so may cause your application to run out of connections.

So does this mean that once we have a response, then it is obligatory to get the stream and close it?

We're seeing some fairly strange issues where hung downloads are eventually swamping the system. This seems like the strongest candidate for a resource leak, but wonder if anyone else has experience with this issue.

As an aside: is it safe to GetResponseStream twice in the assumption that it is the same stream?

+3  A: 

Calling HttpWebResponse.Close implicity closes the response stream.

From the documentation:

The Close method closes the response stream and releases the connection to the resource for reuse by other requests

You must call either the Stream.Close or the HttpWebResponse.Close method to close the stream and release the connection for reuse. It is not necessary to call both Stream.Close and HttpWebResponse.Close, but doing so does not cause an error. Failure to close the stream can cause your application to run out of connections.

And for your double-GetResponseStream question, although the documentation doesn't explicitly mention it, it will always return the same stream object no matter how many times you call it.

Richard Szalay
To confirm: I should do this even though I never got the stream in the first place?
spender
Yes. I've added an update.
Richard Szalay
+1  A: 

Actually, a call to webResponse.Close() will close the response Stream.

The response is IDisposable, I advice you an using statement.

Guillaume
I missed that it was IDisposable. Any clue as to why the Dispose method is private? Is this normal? A using statement seems like an excellent enhancement. +1
spender
[Makes mental note to self not to check for "IDisposability" by cruising intellisense for a Dispose method]
spender