When to call WebResponse.Close()

Sameet picture Sameet · Jul 26, 2009 · Viewed 12.5k times · Source
WebResponse response;
try
{                
 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
 request.Timeout = 20000;
 response = request.GetResponse();

 request = (HttpWebRequest)WebRequest.Create(url2);
 response = request.GetResponse();
}
catch(Exception ex)
{
 //do something
}              
finally
{
}

where should response.Close() be called?

  • after every GetResponse() in try?

  • after last GetResponse() in try - once?

  • in finally block?

Answer

John Saunders picture John Saunders · Jul 26, 2009

None of the above. You should be using a using block:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 20000;
using (WebResponse response = request.GetResponse())
{
    using (var stream = response.GetResponseStream())
    {
        using (var reader = new StreamReader(stream))
        {
            var result = reader.ReadToEnd();
            // Do something with result
        }
    }
}

A using block will ensure that the Dispose method is called, whether or not there is an exception. Dispose will do the same thing as Close.

using (var d = new DisposableClass()){code;}

is equivalent to:

DisposableClass d = null;
try
{
    d = new DisposableClass();
    code;
}
finally
{
    if (d != null)
        ((IDisposable)d).Dispose();
}