是否需要关闭Web请求流?

时间:2012-08-19 08:28:57

标签: c# stream httpwebrequest

哪种方式更受欢迎?

A:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
Stream reqStream = req.GetRequestStream();
reqStream.Write(data, 0, data.Length);
reqStream.Close();

B:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.GetRequestStream().Write(data, 0, data.Length);

2 个答案:

答案 0 :(得分:13)

选项C代替:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
using (Stream reqStream = req.GetRequestStream())
{
    reqStream.Write(data, 0, data.Length);
}

但是,我关闭请求流。它不是绝对必要的可能,但我不想假设 - 特别是,除非你有充分的理由相信它' s 需要(例如文档),实现可能会随着时间的推移而发生变化并且会破坏"懒惰"代码。

如果你发现自己经常这样做,你总是可以写一个实用工具方法(甚至可能作为扩展方法):

public static void WriteRequestData(this WebRequest request, byte[] data)
{
    using (Stream reqStream = request.GetRequestStream())
    {
        reqStream.Write(data, 0, data.Length);
    }
}

然后将其称为:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.WriteRequestData(data);

答案 1 :(得分:1)

我有点迟到了,但这个问题仍然有用。我想补充一下: MSDN Examples还表示/建议在写完成后关闭流。

Stream newStream = myHttpWebRequest.GetRequestStream ();
newStream.Write (byte1, 0, byte1.Length);
Console.WriteLine ("The value of 'ContentLength' property after sending the data is {0}", myHttpWebRequest.ContentLength);
// Close the Stream object.
newStream.Close ();

我喜欢@Jon的例子并遵循类似的模式。