spender
spender

Reputation: 120450

HttpWebResponse: closing the stream

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?

Upvotes: 3

Views: 7238

Answers (3)

SarjanWebDev
SarjanWebDev

Reputation: 533

do something like WCF Connections

//Done with the service, let's close it.
try
{
   if (client.State != System.ServiceModel.CommunicationState.Faulted)
   {
      client.Close();
   }
}
catch (Exception ex)
{
   client.Abort();
}

Upvotes: 0

Richard Szalay
Richard Szalay

Reputation: 84744

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.

Upvotes: 6

Guillaume
Guillaume

Reputation: 13138

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

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

Upvotes: 3

Related Questions