Found some interesting (and frustrating) behavior working with IDisposable today:
Under certain conditions, the following code will produce the following exception:
Unhandled Exception: System.ObjectDisposedException: Cannot write to a closed TextWriter. at System.IO.__Error.WriterClosed() at System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder) at System.IO.StreamWriter.Write(Char[] buffer, Int32 index, Int32 count) at System.IO.TextWriter.WriteLine(String value) at System.IO.SyncTextWriter.WriteLine(String value) at CleanupCalls.Disposable.Finalize()
Exactly which conditions though is hard to pin down. Selectively uncommenting the commented out lines below should reproduce the bug -- although not in a debugger!
It seems like Console's resources are being disposed before the Disposable class's finalizer/destructor gets called.
GC.SuppressFinalize (called from Disposable's Dispose() method) would prevent this from happening, but its still something to be aware of. I have not been able to find anything so far, saying you can't use both Dispose and Finalize, but here's at least one example of where that could cause you problems.
Here's the sample code:
using System; namespace Heisenbug { public class Disposable : IDisposable { //string _description = ""; public Disposable() { //_description = "Foo"; //Console.WriteLine("dispose called"); } ~Disposable() { Console.WriteLine("Finalizer/Destructor Called."); } public void Dispose() { //Console.WriteLine("dispose called"); } } class EntryPoint { static void Main(string[] args) { //Console.WriteLine("pre-call writeline"); UsingDisposable(); //Console.WriteLine("pre-call writeline"); } public static void UsingDisposable() { using(new Disposable()) { //Console.WriteLine("inside the using block"); } } } }