0

My application needs to know when the main thread ends and I found Application.ThreadExit handler. However I can't figure out how to use it. All the examples show Application.ThreadExit += new EventHandler(AppEvents.OnThreadExit);. But this is for Windows Forms, My application is a Console Application. Thank you!

hyWhy
  • 23
  • 5

2 Answers2

0

You can write your code as shown below for console as well :-

Application.ThreadExit += new EventHandler(OnThreadExit);

which will subscribe the event it means whenever thread will exit it will call OnThreadExit method as shown below :-

public static void OnThreadExit(object sender, EventArgs e) 
{
        Console.WriteLine("thread is shutting down.");
}
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Neel
  • 11,625
  • 3
  • 43
  • 61
  • "Application" is underlined and changes color to red.... Which namespace i should use to fix it? – hyWhy Jul 21 '14 at 12:40
0

In console, I always use the SetConsoleCtrlHandler delegate, with DllImport

After class declaration, use:

  private delegate bool ConsoleEventDelegate(int eventType);
        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);

And then in program, set the handler:

var handler = new ConsoleEventDelegate(ConsoleEventCallback);
             SetConsoleCtrlHandler(handler, true);

static bool ConsoleEventCallback(int eventType)
{
    if (eventType == 2)
    {
        //Main thread Console is being closed!
       // handle other threads
    }
    Thread.Sleep(5000);
    return false;
}
Carlos Landeras
  • 11,025
  • 11
  • 56
  • 82
  • That should be a great solution... but i don't understand, where should i declare "var handler"(need to do it in class outside main) – hyWhy Jul 21 '14 at 13:00
  • Wait a minute... This code helps to check, if Console is closed... but i have two threads and need to fire event, when main thread is stopped – hyWhy Jul 21 '14 at 13:23
  • Indeed that what I do on my code. On eventype 2. I check running threads to be canceled before console exits. – Carlos Landeras Jul 21 '14 at 16:06
  • You can declare handler in Main method. When you use setconsolehandler the event is set for app lifetime – Carlos Landeras Jul 21 '14 at 16:07
  • sorry, if you were misunderstood, but additional thread has property IsBackground = false and still works (in pause mode) when main thread terminates... and i need to kill the additional thread just when mainthreadexitevent fires – hyWhy Jul 22 '14 at 05:04
  • And could you tell me, how to fire event number 1000? [Full ctrlhandler class link](https://gist.github.com/bboyle1234/a225218cf4a6825c058c) – hyWhy Jul 22 '14 at 05:26