tags:

views:

22

answers:

1

When using streams, memory consumption is supposed to be the same as the size of the buffer. However, I am not sure how a stream works when I look at the following code, which uses http request and response. (HttpWebRequest to be precise)

Stream requestStream = webRequest.GetRequestStream();

// Here write stuff to the stream, data is a string.
webRequest.ContentLength = data.Length;                
byte[] buffer = Encoding.UTF8.GetBytes(data);

// Obtain request stream from request object so I can send data.
requestStream = webRequest.GetRequestStream();
requestStream.Write(buffer, 0, buffer.Length);                

WebResponse response = webRequest.GetResponse();

I can keep writing stuff to a requestStream, say in a loop, instead of just writing one string, but none of it will reach the target server until the call to webRequest.GetResponse() is made. Then, how (or where) is the data managed by the stream, before the last line is executed ?

+2  A: 

I believe it depends on the value of HttpWebRequest.AllowWriteBufferStreaming. If this property is true (which it is by default), the request data is all buffered up until you ask for the response.

If it's false, the data can be written to the connection as you write it to the stream.

Note that in either case, it would be a good idea to dispose of the stream as normal:

using (Stream requestStream = webRequest.GetRequestStream())
{
    requestStream.Write(buffer, 0, buffer.Length);
}

You should also use a using statement for the response.

Jon Skeet
If used with "using", will the stream be closed before disposal?
Abhijeet Kashnia
@Abhijeet: Disposing of the stream closes it.
Jon Skeet