Я вижу, что многие люди повторяют функциональность Nullable<T>.GetValueOrDefault(T)
.
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();
}
Поместите его в блок finally. Согласно MSDN :
Блок finally полезен для очистка любых ресурсов, выделенных в блок try, а также запуск любого код, который должен выполняться, даже если есть is an exception. Control is always passed to the finally block regardless of how the try block exits.
Обратите внимание, что вложенные блоки с использованием фигурных скобок не требуют фигурных скобок, что улучшает читаемость. Таким образом, можно написать код Джона Саундера:
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
}
VS.NET понимает, что такие вложенные блоки не нуждаются в отступах. Обратите внимание, что если вы знаете кодировку ответа или собираетесь ее игнорировать, WebClient предоставляет более простой API-интерфейс с отсутствующей информацией заголовка, поэтому обнаружение кодировки на основе заголовков (передача / текст) становится невозможным, но в остальном оно работает нормально.
I would suggest the below
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com");
request.Timeout = 20000;
using (var response = request.GetResponse())
{
//Do something with response.
}
request = (HttpWebRequest)WebRequest.Create("http://www.bing.com");
using (var response = request.GetResponse())
{
//Do somehing with response
}
}
catch (Exception ex)
{
//do something
}
finally
{
}