Tuesday, May 03, 2011

C#: Does a Close() automatically call a Flush()

The following C# code always looked a little clunky to me, because a Close() should probably perform a flush as well. I quickly Googled around and my suspicions were confirmed that the Close() method would automatically do a Flush().
Response.Write(qdbXml);
Response.Flush();
Response.Close();
So while cleaning up some other code I removed the Flush() call. Then everything stopped working. I thought it was the other changes I made at first. Chrome gave this helpful message:
Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data.
I restored the Flush() and everything worked great again. The Response object above is a System.Web.Mvc.Controller.Response object which doesn't necessarily work like some other stream objects and needs flushing before closing.
TIL not all stream objects behave alike and I can get in trouble by assuming hastily gathered Googled results apply to me.

No comments: