In a multithreaded setting such as a webserver, in .NET, I generally try to avoid creating contiguous blocks of memory occupying more thank 85KB as that could end up on the large object heap, which could lead to memory problems.
One of my fellow developers is using a loop to write to the Response. OutputStream, without Flushing except at the end of the loop.
Am I correct in thinking that not Flushing in the loop could lead to memory issues? How could I prove this?
That depends on the implementation details of the stream being used. From the MSDN doc on the Stream base class
If the implementator of that stream didn't leave any extra guidance on how to deal with multiple subsequent
Writecalls we should assume it handles those flushing details for you.I assume you find this answer a bit disappointing so dig a bit deeper. As you say your colleague is using
Response.OutputStreamlet's see what the underlying implementation of that property is.So it is using the
Streamfrom something in_httpWriter. That field turns out to hold a reference to an instance of anHttpWriter. It'sOutputStreamproperty get initialized in the constructor:The class
HttpResponseStreamis internal but we can use ILSpy to pry it open. ItsWritemethod defers the implementation back to this HttpWriter's method:As you can see the byte[] data is being handed off to an method that further copy and stores the data with the help
HttpResponseUnmanagedBufferElementwhich copies the bytes to memory with anMarshal.Copyto a buffer that is unmanaged memory. That memory seems to be allocated in blocks of around 16K for an integrated pipeline and around 31K for the rest.With that I don't expect the Stream to allocate so much memory that its internal structures end-up on the LOH because by the looks of it it only makes managed -> unmanaged memory copies.
Leaves us with your idea to regularly call
Flushin the loop. TheHttpResponseStreamhas this implementation:where
_writeris the earlier discoveredHttpWriter. Its implementation isThat is right, calling flush will only waste CPU cycles. It will not help the stream in clearing its buffers sooner, despite the promising documentation in MSDN.