C# 控制台应用程序在按下 CTRL+C 且没有 while 循环之前不会退出

问题描述 投票:0回答:1

因为

while()
它会产生高 CPU 使用率,我如何运行异步方法但等到按下 CTRL+C 后再退出程序?

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...");
    }
}
c# async-await console-application
1个回答
0
投票

一个快速的“黑客”方法是添加

Task.Delay
,这样你的主线程就不会使用资源:

Task.Run(async () =>
{
    // Do your work here
    for (int i = 0; ; i++)
    {
        Console.WriteLine(i);
        await Task.Delay(500);
    }
});

Console.WriteLine("Press Ctrl+C to exit");
while (true)
{
    await Task.Delay(1000);
}

更合适的方法是使用

TaskCompletionSource
:

var cts = new TaskCompletionSource();

_ = Task.Run(async () =>
{
    // Do your work here
    for (int i = 0; i < 5; i++)
    {
        Console.WriteLine(i);
        await Task.Delay(500);
    }

    // Done: report it as done
    cts.TrySetResult();
});

Console.WriteLine("Press Ctrl+C to exit or wait until the app finishes");
await cts.Task;
© www.soinside.com 2019 - 2024. All rights reserved.