Is there any way to stop a .NET console app from being closed? I’ve got an app that follows this pattern:
while (true)
{
string x = Console.ReadLine();
StartLongRunningTaskOnSeparateThread(x);
}
The problem is that it’s possible to close the console window (and therefore cut off the long running task). Is there an equivilent of the Forms.OnClosing event for console apps?
EDIT – I’m not trying to create something that’s impossible to kill, just maybe give a warning message e..g “hey i’m not done yet. are you sure you want to close me?”
EDIT2 – Preventing an untimely exit via the ‘x’ button is more important than blocking Ctrl-C (I used Console.TreatControlCAsInput = true;). Assume for this purpose that anyone who fires up task manager wants to kill the program so much that they deserve to be able to. And that the end user would rather see a warning than accidentally cancel their long running task.
Here is my attempt to solve this problem. Task Manager can still close the application though. But, my thought was to try and detect when it is being closed and then relaunch it. However, I didn’t implement that part.
The following program will detect a CTRL-C && CTRL-BREAK and will keep on going.
EDIT: Removed the “X” Button