If OnWriteToStreamAsync took a StreamWriter arg instead of a Stream, then media type formatters wouldn't have to create their own (Daniel's
VCard example creates one StreamWriter per contact, although this could be optimized).
And if you wanted to write bytes (as Daniel's
ContactPng formatter does), you just upcast the StreamWriter to Stream. [Won't work; see below]
So passing in a StreamWriter will save unnecessary object creation. But the
big win is that the framework would hold on to the reference to the StreamWriter for the lifetime of the response. This would solve the problem of media-type-formatter-created StreamWriters going out of scope and running the risk of finalization and
closing the underlying stream (System.Web.HttpResponseStream) prematurely, as I have
highlighted in a related post.
Another idea is to pass in System.Web.HttpResponseStream instead of Stream, and have it expose public methods that support the writing of both text and bytes.
awebb
Member
204 Points
91 Posts
OnWriteToStreamAsync should take a StreamWriter arg
Mar 01, 2012 06:44 AM|LINK
If OnWriteToStreamAsync took a StreamWriter arg instead of a Stream, then media type formatters wouldn't have to create their own (Daniel's VCard example creates one StreamWriter per contact, although this could be optimized).
And if you wanted to write bytes (as Daniel's ContactPng formatter does), you just upcast the StreamWriter to Stream. [Won't work; see below]
So passing in a StreamWriter will save unnecessary object creation. But the big win is that the framework would hold on to the reference to the StreamWriter for the lifetime of the response. This would solve the problem of media-type-formatter-created StreamWriters going out of scope and running the risk of finalization and closing the underlying stream (System.Web.HttpResponseStream) prematurely, as I have highlighted in a related post.
awebb
Member
204 Points
91 Posts
Re: OnWriteToStreamAsync should take a StreamWriter arg
Mar 01, 2012 06:52 AM|LINK
StreamWriter doesn't derive from Stream. Rats!
awebb
Member
204 Points
91 Posts
Re: OnWriteToStreamAsync should take a StreamWriter arg
Mar 01, 2012 06:55 AM|LINK
Another idea is to pass in System.Web.HttpResponseStream instead of Stream, and have it expose public methods that support the writing of both text and bytes.
awebb
Member
204 Points
91 Posts
Re: OnWriteToStreamAsync should take a StreamWriter arg
Mar 02, 2012 06:50 AM|LINK
Another idea, for if you don't want to (or can't) add public methods to HttpResponseStream...
Pass both a Stream arg (named binaryWriter) and a StreamWriter arg (named textWriter) to OnWriteToStreamAsync.
Again the win is twofold:-