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?
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.
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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With