You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过任意按键中断运行中的Timer,阻止程序自动退出?

解决Timer倒计时中断问题:按下任意键阻止程序关闭

我来帮你搞定这个Timer中断的难题!你原来的实现思路有个关键问题——把按键监听逻辑放到了Timer的回调函数里,这不仅没法正常捕获用户输入,还没办法正确停止Timer的倒计时。

原代码存在的问题

private static void CommandExit() { 
    Console.WriteLine("Thank you for your input!"); 
    Console.WriteLine("The programm will now close. \r\n"); 
    var countdown = 5; 
    var myTimer = new Timer(state => { 
        Console.WriteLine("Program is closing in: '{0}' ", countdown); 
        countdown--; 
        if (countdown <= 0) { 
            Environment.Exit(0); 
        } 
        if (countdown != null) { 
            Console.WriteLine("Press any Key to interrupt the closing process."); 
            var breakuptoken = Console.ReadKey(); 
            if (breakuptoken != null) { 
                //SOMETHING IS MISSING HERE 
            } 
        } 
    }, null,0, 1000); 
}
  • Timer的回调是在ThreadPool线程中执行的,而Console.ReadKey()需要在主线程才能正常捕获用户输入,放在回调里根本起不到监听作用
  • .NET的Timer没有直接的Stop()方法,但我们可以通过修改它的触发间隔来停止计时,这正是你代码里缺失的核心逻辑

修正后的解决方案

private static void CommandExit() { 
    var countdown = 5; 
    Console.WriteLine("Thank you for your input!"); 
    Console.WriteLine("The programm will now close. \r\n"); 
    Console.WriteLine("Press any Key to interrupt the closing process.");
    
    var myTimer = new Timer(state => { 
        Console.WriteLine("Program is closing in: '{0}' ", countdown); 
        countdown--; 
        if (countdown <= 0) { 
            Environment.Exit(0); 
        } 
    }, null, 0, 1000); 
    
    Console.ReadKey(); 
    myTimer.Change(Timeout.Infinite, Timeout.Infinite); 
}

关键修正点说明

  • 把Console.ReadKey()移到主线程:这样能正常捕获用户的任意按键操作
  • 调用myTimer.Change(Timeout.Infinite, Timeout.Infinite):这是.NET Timer的"停止"方式,把触发间隔改成无限大,Timer就不会再执行回调,自然也就不会触发程序退出的逻辑
  • 提前提示用户可以按键中断:优化了交互体验,让用户一开始就知道有中断选项

内容的提问来源于stack exchange,提问作者ChriRo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:26:29