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
{
}
应该在哪里调用response.Close()?
在try?
在try-once中的最后一次GetResponse()之后?
答案 0 :(得分:21)
以上都不是。您应该使用using
块:
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
}
}
}
using
块将确保调用Dispose方法,无论是否存在异常。 Dispose将执行与Close相同的操作。
using (var d = new DisposableClass()){code;}
相当于:
DisposableClass d = null;
try
{
d = new DisposableClass();
code;
}
finally
{
if (d != null)
((IDisposable)d).Dispose();
}
答案 1 :(得分:1)
把它放在finally块中。根据{{3}}:
finally块非常有用 清理分配的任何资源 try块以及运行任何块 即使存在必须执行的代码 是一个例外。总是控制 无论如何传递给finally块 如何退出try块。
答案 2 :(得分:0)
请注意,使用块嵌套不需要花括号,从而提高了可读性。所以John Saunder的代码可以写成:
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 - 缺少头信息,因此基于头部(传输/文本)编码检测变得不可能,但是否则它可以正常工作。
答案 3 :(得分:-1)
我建议如下
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
{
}