class MainClass
{
private static bool keepRunning = true;
public static void Main(string[] args)
{
Console.CancelKeyPress += delegate(object? sender, ConsoleCancelEventArgs e) {
e.Cancel = true;
MainClass.keepRunning = false;
};
while (MainClass.keepRunning) {
// Do your work in here, in small chunks.
// If you literally just want to wait until Ctrl+C,
// not doing anything, see the answer using set-reset events.
}
Console.WriteLine("exited gracefully");
}
}
此代码与第一个示例的区别在于, e.Cancel 设置为 true,这意味着在委托之后继续执行。如果运行,程序将等待用户按下Ctrl+C。当发生这种情况时, keepRunning 变量的值会改变,从而导致 while 循环退出。这是一种让程序正常退出的方法。