因为
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...");
}
}
一个快速的“黑客”方法是添加
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;