This project is read-only.

Question about OnWriteToStream

Topics: Web Api
Dec 20, 2011 at 9:27 AM

In your CSV media formatter code (in the WCF Web API chm file), you do this:-

var writer = new StreamWriter(stream);
writer.WriteLine("{0},{1},{2}", Escape(contact.ContactId), Escape(contact.Name), Escape(contact.Email));

You don't ever close the writer because you (presumably) want to keep the underlying stream open.  But I was wondering what would happen if a garbage collection crept in immediately after 'writer' went out of scope... would it not finalize the StreamWriter, disposing/closing it and also closing the underlying stream?

Side note #1: I see in your source that this relates to an unresolved issue: "TODO: CSDMain 235508: Should formatters close write stream on completion or leave that to somebody else?"

Side note #2: as a test, I called .Close() and .Dispose() on the 'stream' arg that is passed to OnWriteToStream before creating a StreamWriter based on the stream, and bizarrely my code still managed to write to the stream.  I was expecting an ObjectDisposedException or whatever it is.

Can you shed any light on your current thinking re. write-stream closing?

Dec 20, 2011 at 10:05 AM

Ok I'm beginning to understand... Stream is actually a BufferManagerOutputStream, and its Close and Flush methods don't actually do anything.