Allowing a batch to finish gracefully, after the user presses Ctrl+C   Leave a comment

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:

  1. Declare a boolean flag:
    private bool canceled = false;
  2. Subscribe to the CancelKeyPress event:
    Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
  3. 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;
  4. In your for loop, which could be a conversion, migration, build, report &c, first check the exit condition: If met, exit gracefully:
    if (canceled)

Posted June 13, 2011 by pricklymaster in Coding techniques

Tagged with , , , , ,