Don't Forget to Flush!
current location: Office
current mood: energetic
current song: The sound of compiling code...
I saw something new today that I haven't seen since my C++ days: a stream that needed to be flushed.
I have to admit, this one boggled me for about 15 minutes before I realized what was going on. Then I caught a mistake I haven't made in years: I forgot to close an open StreamWriter.
The function is a simple one. It iterates through decorated methods in my Program.cs file, finds the command name through reflection (thanks to a colleague of mine), and streams the command name to a text file for later review (after some collection manipulation and sorting). Here was the original method:
As you can see, it looks pretty innocent. Except for one small problem: In a collection of 60 strings, only 44 1/2 of the strings were being streamed! Yes, you saw that correctly. Only 44.5 of the 60 total strings were being written to the text file. Then I had a C++ flashback that threw me into a post traumatic stress episode...
Back in C++ we had to routinely "flush" our streams to make sure all the data made it safely to its destination. I don't ever recall having to explicitly flush ANYTHING in C# or, dare I say it, VB.Net (<gasp>)! Then I looked back at my code and slapped myself square on the face.
I forgot to close the stupid stream :( 15 minutes down the toilet because I forgot to flush (pun intended). In C#, making a call to StreamWriter.Close() causes an implicit flush to take place. No, I don't know or understand the details yet. I just know it happens.
With a single line of code: sw.Close(); I was able to successfully stream all of my commands to the text file. Here is the finished product:
Not much of a difference in implementation, huh? But a HUGE difference in effect.




