I have been looking for a way to detect when the a console application has ended. I want the ability to do some cleanup. Similar to Application.ApplicationExit in forms applications. I've scoured google, code project, msdn, etc. but no solid solution.
I thought about simply launching a cleanup thread at the start of the program and have it Join the main thread. Once that happens perform cleanup. I tried a test application (see code below):
staticvoid Main(string args)
Thread cleanupThread = new Thread(cleanupThreadStart);
privatestaticvoid cleanupThreadStart(object state)
Thread mainThread = (Thread)state;
Console.WriteLine("cleanupThreadStart: Waiting for main thread to exit.");
Oddly, this solution works from within VS when I start with debugging (F5), meaning that the main thread will end and the cleanup thread will complete the join and I'll see the console printout. However if I start without debugging (ctrl+F5 or simply run the executable directly) the program hangs because the main thread ends but the cleanup thread never completes the Join. I've tried attaching to the process from within VS during the hang and I can see that the main thread is no longer present but the cleanup thread is still waiting for the Join to complete.
Does anybody know why this works with debugging active but not without it? Does anybody have any other clever way of detecting that the application is about to end (similar to Application.ApplicationExit)?
For now I've got a workaround to just create my own "main" thread which executes the normal application code. Then my cleanup thread joins with this thread before cleanup. This seems to work fine.
When the debugger is attached, it will keep the main-thread alive, since you're debugging. Without the debugger, the main-thread is halted. The application will close as soon as all foreground threads close.
There is no event that says that a console-application is about to be aborted with Ctrl-C. The mainthread is simply terminated; hence it will not execute any events.
Bastard Programmer from Hell If you can't read my code, try converting it here[^]
When I load the data onto the gridView if the string contains a newline character, and the first line ("\r\n"), the grid in the first row of the gridView down the line when viewed slightly inconvenient to stretch the new grid see lines that are hidden, you want to stop in the gridView grid phenomenon is not ? (Ie if there is a newline character and the beginning of a line also appears on a single line of gridView), instead I have to write more code to browse all the columns in the grid newline character removed and the beginning of the line . Can you help me ?
Last Visit: 31-Dec-99 19:00 Last Update: 10-Dec-16 4:19