C# Console app do not exit until CTRL+C pressed without while loop

66 Views Asked by At

because the while() it produce high CPU usage, how I can run async method but wait until CTRL+C pressed before the program exit?

class Program
{
    public static bool isRunning = true;
    static void Main(string[] args)
    {
        Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
        // run async method...
        Console.WriteLine("-> Press CTRL+C to Exit");
        while (isRunning) { } // <- wait but without this
    }

    static void Console_CancelKeyPress(object? sender, ConsoleCancelEventArgs e)
    {
        e.Cancel = true;
        isRunning = false;
        Console.WriteLine("CancelKeyPress fired, exit...");
    }
}
0

There are 0 best solutions below