1

我现在正在重构一些代码,发现以下函数:

public static StreamReader DoWebRequest(string url, string method)
{
    HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
    req.Method = method;
    req.Timeout = System.Threading.Timeout.Infinite;
    HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
    return new StreamReader(resp.GetResponseStream());
}

然后

string result = Helper.DoWebRequest(ServerUrl, "GET").ReadToEnd();

我经常使用流,并且总是将HttpWebResponse resp = req.GetResponse()流式阅读器放入 using 块中。但是在这种特殊情况下我应该怎么做呢?上面的代码是否可以,或者最好将 StreamReader 分配给新变量并在调用 ReadToEnd() 后显式关闭它;(或使用块内部)像这样:

using(StreamReader sr = Helper.DoWebRequest(ServerUrl, "GET"))
{
  string result = sr.ReadToEnd();
}

谢谢

4

1 回答 1

1

Well, you can always write another function that does both:

public static String ReadToEndAndClose(this StreamReader stream)
{
    using(var sr = stream)
    {
        return sr.ReadToEnd();
    }
}
于 2013-06-10T08:38:51.223 回答