3

We do have console application:

namespace MyApplication
{

    public void Main()
    {
        try
        {
            AppDomain.CurrentDomain.ProcessExit  += (sender, eventArgs) => Stop();

            Start();
            Console.ReadLine();
        }
        finally
        {
            Close();
        }
    }

    public void Start() 
    {
        //...
    }

    public void Stop() 
    {
        //...
    }
}

So if application is stopped proper (by pressing Enter in console window) Close() method is called from finally & AppDomain.CurrentDomain.ProcessExit

But when application is closed by Close button or terminated from Task Manager Close() method is not called at all.

Questions are:

  1. Why finally block doesn't work?
  2. How to handle console closing by Close button?

UPD Even object's destructor is not called:

public class Watcher
{
    Action _start;
    Action _stop;
    public Watcher(Action start, Action stop)
    {
        _start = start;
        _stop = stop;
    }

    ~Watcher()
    {
        _stop();
    }

    public void Start()
    {
        _start();
    }
}

// And using as:
var w = new Watcher(Start, Stop);
w.Start();

Destructor is not called!

ili
  • 722
  • 1
  • 4
  • 15
  • Please refer to http://blogs.msdn.com/b/jmstall/archive/2006/11/26/process-exit-event.aspx – Zen Dec 29 '15 at 08:43

1 Answers1

1
  1. The finally block is only reached when the Console.ReadLine() call is completed which only happens when you press enter on the keyboard. There is no other way to reach the code in the finally block.

  2. To handle the close button you will need to subscribe to the Win32 event as .NET does not provide direct bindings for it. Please see suggestions in this question: Capture console exit C#

Community
  • 1
  • 1
Gabriel Sadaka
  • 1,748
  • 1
  • 15
  • 19