James Wilson
James Wilson

Reputation: 5150

Safely exit console-application?

I have a console application that will be ran on the weekends. And when I come back into work I will need to safely terminate it.

It is running a loop and modifying files by moving them, and updating a database.

I cannot just simply Ctrl-Z to exit it I am assuming as this could stop the program in the middle of working on a file?

Is there a safe way for me to say press the 'c' key to set my runLoop boolean to false so this would exit my loop properly or is there a better way?

static void Main(string[] args)
{
     bool runLoop = true;

     while (runLoop)
     {
          // bunch of code
          // moving files, updating database.
     }
}

What is a safe way to terminate this loop and ensure the currently running file will be finished successfully?

Upvotes: 2

Views: 971

Answers (1)

Servy
Servy

Reputation: 203812

You can easily add a handler to an event exposed to you for when that command is pressed and use it to signal cancellation:

bool runLoop = true;

ManualResetEvent allDoneEvent = new ManualResetEvent(false);
Console.CancelKeyPress += (s, e) =>
{
    runLoop = false;
    allDoneEvent.WaitOne();
};

int i = 0;
while (runLoop)
{
    Console.WriteLine(i++);
    Thread.Sleep(1000);  //placeholder for real work
}

//for debugging purposes only
Console.WriteLine();
Console.WriteLine("press any key to exit . . .");
Console.ReadKey(true);

allDoneEvent.Set();

Note that the entire process will be killed when that event handler finishes, so you also need to ensure that that event handler is kept running until the rest of the program is able to finish gracefully.

Upvotes: 4

Related Questions