I am trying to ensure my class gets disposed by implementing IDisposable
. However I have found that if I close the console by pressing the X then the dispose method is not called. How can I ensure it is called in this instance?
using System;
using System.IO;
namespace Testing
{
public class Disposable : IDisposable
{
private StreamWriter output = File.CreateText(@"test.txt");
public Disposable()
{
output.WriteLine("Created!");
}
public void Dispose()
{
output.WriteLine("Disposed!");
output.Dispose();
}
}
static class Program
{
static void Main(string[] args)
{
using (new Disposable())
{
Console.ReadLine();
}
}
}
}
You can test this behaviour with the above. If you execute the program and press any key, the program terminates properly and the file will contain:
Created!
Disposed!
However if you execute the program and close the console by pressing the X the file will be empty as the stream does not get disposed and/or flushed.