0

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.

maddisoj
  • 576
  • 6
  • 16
  • If the process is terminated, then the process is terminated. There is nothing you can do. – Yacoub Massad Dec 04 '15 at 12:04
  • @YacoubMassad It's not like I'm sending a kill signal where I would expect this type of behaviour. I'm sending a simple interrupt/terminate signal... or I would be if this wasn't Windows. – maddisoj Dec 04 '15 at 12:08
  • You might want to read this: http://stackoverflow.com/questions/12106349/memory-leaks-when-program-is-closed-with-x – EylM Dec 04 '15 at 12:11

0 Answers0