Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep a .NET console app running?

People also ask

How do I stop my console from closing in C#?

Try Ctrl + F5 in Visual Studio to run your program, this will add a pause with "Press any key to continue..." automatically without any Console.

Why does console close after execution C#?

Because it's finished. When console applications have completed executing and return from their main method, the associated console window automatically closes.


you always want to prevent using while loops, especially when you are forcing the code to recheck variables. It wastes CPU resources and slows down your program.

I would definitely say the first one.


Alternatively, a more simple solution is just:

Console.ReadLine();

You can do that (and remove the CancelKeyPress event handler) :

while(!_quitFlag)
{
    var keyInfo = Console.ReadKey();
    _quitFlag = keyInfo.Key == ConsoleKey.C
             && keyInfo.Modifiers == ConsoleModifiers.Control;
}

Not sure if that's better, but I don't like the idea of calling Thread.Sleep in a loop.. I think it's cleaner to block on user input.


I prefer using the Application.Run

static void Main(string[] args) {

   //Do your stuff here

   System.Windows.Forms.Application.Run();

   //Cleanup/Before Quit
}

from the docs:

Begins running a standard application message loop on the current thread, without a form.


It's also possible to block the thread / program based on a cancellation token.

token.WaitHandle.WaitOne();

WaitHandle is signalled when the token is cancelled.

I have seen this technique used by the Microsoft.Azure.WebJobs.JobHost, where the token comes from a cancellation token source of the WebJobsShutdownWatcher (a file watcher that ends the job).

This gives some control over when the program can end.


Seems like you're making it harder than you need to. Why not just Join the thread after you've signaled it to stop?

class Program
{
    static void Main(string[] args)
    {
        Worker worker = new Worker();
        Thread t = new Thread(worker.DoWork);
        t.IsBackground = true;
        t.Start();

        while (true)
        {
            var keyInfo = Console.ReadKey();
            if (keyInfo.Key == ConsoleKey.C && keyInfo.Modifiers == ConsoleModifiers.Control)
            {
                worker.KeepGoing = false;
                break;
            }
        }
        t.Join();
    }
}

class Worker
{
    public bool KeepGoing { get; set; }

    public Worker()
    {
        KeepGoing = true;
    }

    public void DoWork()
    {
        while (KeepGoing)
        {
            Console.WriteLine("Ding");
            Thread.Sleep(200);
        }
    }
}

Of the two first one is better

_quitEvent.WaitOne();

because in the second one the thread wakes up every one millisecond will get turned in to OS interrupt which is expensive