5

哪种方式更可取?

A:

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

乙:

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

2 回答 2

13

选项 C 改为:

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

但是,是的,我关闭请求流。它可能不是绝对必需的,但我不想假设 - 特别是,除非你有充分的理由相信它不是必需的(例如文档),否则实现可能会随着时间而改变并破坏“懒惰”代码之后。

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

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);
于 2012-08-19T08:30:57.507 回答
1

我参加聚会有点晚了,但这个问题仍然很重要。我想补充一点: MSDN 示例还演示/建议在写入完成时关闭流。

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 的例子并遵循类似的模式。

于 2014-02-06T21:41:36.157 回答