Jhonathan
Jhonathan

Reputation: 330

How to keep a .NET console app running without looping?

Consider a Console application that starts up some services in a separate thread. All it needs to do is wait for the user to press Ctrl+C to shut it down.

I already tried some examples, but all examples work with "do while".

Consider this code :

static void Main(string[] args)
{
    for (long ContactId = 0; ContactId < 1000; ContactId++)
    {
        try
        {
            Task.WaitAll(CreateJson(ContactId));
        }
        catch (Exception ex)
        {
            System.IO.File.AppendAllText("error.txt", ContactId + "\n", encoding);
        }
    }

    Console.WriteLine("Finalizado em " + watch.Elapsed + "");
    Console.ReadKey();
 }

How can I do some "listener" to stop the all the process and exit the console?

I already tried this example but not works fine for me (How to keep a .NET console app running?)

Thanks

Upvotes: 0

Views: 1642

Answers (1)

quetzalcoatl
quetzalcoatl

Reputation: 33506

There's an event on Console class that will help you detect that user pressed control+c

Console.CancelKeyPress += myHandler;

void myHandler(object sender, ConsoleCancelEventArgs args)
{
    // do something to cancel/interrupt your jobs/tasks/threads
}

This event is raised when user presses Ctrl+C or Break keys. IIRC, the event is invoked asynchronously from the Main() thread, so you will get it even if your "Main" function wandered deep into some other code and is grinding something.

I mean, if your main thread sleeps in Task.WaitAll, you will still get that event if keys are pressed.

Another thing is, how to cancel your tasks. That depends on how your long running tasks are organized. Probably CancellationTokenSource will be your friend if you use Tasks, Threads or some your own things. Tasks support CancellationTokens/Source. You can pass the token as one of arguments to the Factory or Task.Run or similar task-creating methods. However, you also need to ensure that the token.ThrowIfCancellationRequested() is used in the tasks' inner code. If you use some libraries to work for you, they may happen to not support CancellationToken, then you will need to research how to cancel/interrupt them properly.

Upvotes: 3

Related Questions