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

C#使用System.Timers.Timer实现的控制台计时程序无法刷新标题问题求助

问题根因
  • 仅在初始化阶段对Console.Title赋值了一次,计时变量更新后没有同步重新设置控制台标题,导致展示内容永远是初始值
  • 代码存在拼写错误:启动Timer时用了不存在的变量lockcount.Enabled = true,你定义的Timer实例名是clockcount,该错误会导致Timer压根没启动,计时逻辑不会执行
  • 计时变量引用混乱:回调函数里current_seconds部分加了Constants.前缀,current_minute、current_hour没加,如果三个变量都定义在Constants类下,未加前缀的修改操作实际是操作局部变量,全局的计时变量根本不会更新
  • 回调里的GC.Collect()属于完全多余的操作,每秒强制GC会严重浪费性能,直接删除即可
  • 额外注意:控制台程序需要阻塞主线程避免直接退出,否则Timer启动后程序会立刻结束,看不到更新效果
修复后的实现代码

全局变量及初始化代码

public static class Constants
{
    public static int current_hour = 0;
    public static int current_minute = 0;
    public static int current_seconds = 0;
}
// 初始化标题
Console.Title = $"Elapsed time: {Constants.current_hour.ToString().PadLeft(2, '0')}:{Constants.current_minute.ToString().PadLeft(2, '0')}:{Constants.current_seconds.ToString().PadLeft(2, '0')}";

计时回调函数

public static void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
    Constants.current_seconds++;
    if (Constants.current_seconds == 60)
    {
        Constants.current_seconds = 0;
        Constants.current_minute++;
        if (Constants.current_minute == 60)
        {
            Constants.current_minute = 0;
            Constants.current_hour++;
        }
    }
    // 每次更新时间后重新设置控制台标题
    Console.Title = $"Elapsed time: {Constants.current_hour.ToString().PadLeft(2, '0')}:{Constants.current_minute.ToString().PadLeft(2, '0')}:{Constants.current_seconds.ToString().PadLeft(2, '0')}";
}

Timer启动代码

System.Timers.Timer clockcount = new System.Timers.Timer();
clockcount.AutoReset = true;
clockcount.Interval = 1000;
clockcount.Elapsed += Timer_Elapsed;
clockcount.Enabled = true; // 修正变量名拼写错误
clockcount.Start();

// 阻塞主线程,避免程序直接退出
Console.ReadKey();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 21:48:04