I was put in a situation where the abrupt batch end will still have to be handled. More precisely, after the user presses Ctrl+C to stop the batch, the program would have to save a log and then exit gracefully.
So, without further ado:
- Declare a boolean flag:
private bool canceled = false; - Subscribe to the CancelKeyPress event:
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress); - In the event handler, set the flag and cancel the CancelKeyPress event:
private void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
canceled =true;
Console.WriteLine(“\r\nCtrl-C was pressed, process interrupted by user”);
e.Cancel =true;
} - In your for loop, which could be a conversion, migration, build, report &c, first check the exit condition: If met, exit gracefully:
if (canceled)
{
EndLogging();
break;
}