I tried to further narrow down the problem in Flush StreamWriter at the end of its lifetime implementing a singleton-like self-closing StreamWriter
:
class Foo : System.IO.StreamWriter
{
private static readonly Foo instance = new Foo( "D:/tmp/test" );
private Foo( string path )
: base( path )
{
}
~Foo()
{
this.Close();
}
public static Foo Instance
{
get
{
return instance;
}
}
}
The intended effect is that in a sample program like
class Program
{
private static void Main( string[] args )
{
Foo.Instance.Write( "asdf\n" );
}
}
the garbage collector causes the instance of Foo
to be closed.
This does not work. Apparently, the StreamWriter
is already gone when Foo
's destructor runs, and I get a System.ObjectDisposedException
.
How do I call Close()
on the stream in an appropiate way and prevent loss of data?