Wednesday, June 29, 2011

Coconut

Simple, but little painful snare regarding Streams and StreamWriters.

Let's imagine we have a function that print some data to a TextWriter:

void Print(TextWriter writer)
{
 // ...
}

Also we have a stream (e.g. Http output stream), which we want to use to print in data. So, we'll write something like:

using (Stream stream = GetOutputStream()){
  var streamWriter = new StreamWriter(stream);
  Print(streamWriter);
}

This code is fair enough - as far as StreamWriter uses the disposed stream, there should not be any resource leaks as far as we're disposing the thread. But there is some bug which can lead to data losses.