gpt4 book ai didi

c# - 在 Debug模式下给定 ctrl + c 时,控制台应用程序不会退出

转载 作者:行者123 更新时间:2023-11-30 14:22:25 26 4
gpt4 key购买 nike

当我在 Release 中运行以下命令时,按 CTRL + C 成功终止应用程序。

在 Debug 中运行时,按 CTRL + C 会在下面的 while 循环中挂起。

为什么?有解决办法吗?

static void Main(string[] args)
{
while (true)
{
// Press CTRL + C...
// When running in Release, the app closes down
// When running in Debug, it hangs in here
}
}

最佳答案

实现此目的的一种方法是使用 Console.CancelKeyPress

Occurs when the Control modifier key (Ctrl) and either the ConsoleKey.C console key (C) or the Break key are pressed simultaneously (Ctrl+C or Ctrl+Break).

When the user presses either Ctrl+C or Ctrl+Break, the CancelKeyPress event is fired and the application's ConsoleCancelEventHandler event handler is executed. The event handler is passed a ConsoleCancelEventArgs object


示例

private static bool keepRunning = true;

public static void Main(string[] args)
{
Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) {
e.Cancel = true;
keepRunning = false;
};

while (keepRunning)
{
// Do stuff
}
Console.WriteLine("exited gracefully");
}

关于c# - 在 Debug模式下给定 ctrl + c 时,控制台应用程序不会退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49664024/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com