How to properly dispose of a WebResponse instance?

Marcus picture Marcus · Dec 11, 2009 · Viewed 10.4k times · Source

Normally, one writes code something like this to download some data using a WebRequest.

using(WebResponse resp = request.GetResponse())  // WebRequest request...
   using(Stream str = resp.GetResponseStream())  
      ; // do something with the stream str

Now if a WebException is thrown, the WebException has a reference to the WebResponse object, which may or may not have Dispose called (depending on where the exception has happened, or how the response class is implemented) - I don't know.

My question is how one is supposed to deal with this. Is one supposed to be coding very defensively, and dispose of the response in the WebException object (that would be a little weird, as WebException is not IDisposable). Or is one supposed to ignore this, potentially accessing a disposed object or never disposing an IDisposable object? The example given in the MSDN documentation for WebException.Response is wholly inadequate.

Answer

Christian Hayter picture Christian Hayter · Dec 11, 2009

I have had a quick peek with Reflector, and can now say:

  • WebResponse, being an abstract class, delegates all its closing/disposing behaviour to its derived classes.
  • HttpWebResponse, being the derived class you are almost certainly using here, in its close/dispose methods, is only concerned with disposing the actual response stream. The rest of the class state can be left to the GC's tender mercies.

It follows that it's probably safe to do whatever you like with regard to exception handling, as long as:

  • When you read the response stream from WebResponse in the try block, enclose it in a using block.
  • If you read the response stream from WebException in the catch block, enclose it in a using block as well.
  • There is no need to worry about disposing of WebException itself.