Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to call WebResponse.Close()

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?
like image 862
Sameet Avatar asked Jul 26 '09 12:07

Sameet


People also ask

Do you need to close HttpWebRequest?

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.


2 Answers

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();
}
like image 78
John Saunders Avatar answered Sep 29 '22 14:09

John Saunders


Put it in the finally block. As per MSDN:

The finally block is useful for cleaning up any resources allocated in the try block as well as running any code that must execute even if there is an exception. Control is always passed to the finally block regardless of how the try block exits.

like image 45
marco0009 Avatar answered Sep 29 '22 14:09

marco0009