加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在调试模式下给出ctrl c时,控制台应用程序不会退出

发布时间:2020-12-16 01:26:23 所属栏目:百科 来源:网络整理
导读:当我在Release中运行以下内容时,按下CTRL C会成功终止该应用程序. 在Debug中运行时,按下CTRL C会在下面的while循环中挂起. 为什么?有没有解决的办法? static void Main(string[] args){ while (true) { // Press CTRL + C... // When running in Release,t
当我在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");
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读