Let's say we have the following code:
class Program {
static void Main(string[] args) {
FileStream fs = new FileStream("DataFile.dat", FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
sw.Write("Hi there");
// <-----doesn't call sw.Dispose()
GC.Collect(); // not necessary to force GC run as MDAs should break anyway, but still call it to be safe and hopefully can throw an run time exception
Console.ReadLine();
}
}
Notice that the StreamWriter’s constructor takes a reference to a Stream object as a parameter, allowing a reference to a FileStream object to be passed as an argument. Internally, the StreamWriter object saves the Stream’s reference. When you write to a StreamWriter object, it internally buffers the data in its own memory buffer. When the buffer is full, the StreamWriter object writes the data to the Stream.
We know that we supposed to call sw.Dispose();, becuase if the FileStream object were finalized first, it would close the file. Then when the StreamWriter object was finalized, it would attempt to write data to the closed file, throwing an exception.
So I tick on StreamWriterBufferredDataLost checkbox of Managed Debugging Assistants (MDAs) in visual studio to make the program breaks when it detect Dispose is not explicitly called.
But when I run my code, it doesn't break, MDAs doesn't pop up, what's going on?