【问题标题】:Elapsed time chronometer doesn't get refreshed constantly经过时间计时器不会不断刷新
【发布时间】:2021-11-30 11:58:02
【问题描述】:

我制作了一个计时器,可以每秒刷新 Console.Title 上的时间,但它不起作用,它永远不会刷新。它总是在 00:00:00。 每秒刷新一次怎么办?谢谢!

public static int current_hour = 0;
public static int current_minute = 0;
public static int current_seconds = 0;
Console.Title = $"Elapsed time: {current_hour.ToString().PadLeft(2, '0')}:{current_minute.ToString().PadLeft(2, '0')}:{current_seconds.ToString().PadLeft(2, '0')}";

这里是函数。

public static void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
Constants.current_seconds++;
if (Constants.current_seconds.Equals(60))
{
      current_seconds = 0;
      current_minute++;
      if (Constants.current_minute.Equals(60))
      {
           current_minute = 0;
           current_hour++;
      }
}
     GC.Collect();
}

这是用户在控制台上按下 Start 时运行经过时间的代码

System.Timers.Timer clockcount = new System.Timers.Timer();
clockcount.AutoReset = true;
clockcount.Interval = 1000;
clockcount.Elapsed += Timer_Elapsed;
lockcount.Enabled = true;
clockcount.Start();

【问题讨论】:

  • 计时器没有那么精确。不要增加变量,而是使用DateTime.NowStopwatch 以获得更好的时机。
  • 你在哪里更新Console.Title?我只能在您的代码中看到它被初始化一次。如果您希望它在计时器触发时更新,您需要从Timer_Elapsed() 内部直接(或间接)更新它。

标签: c# chronometer system.timers.timer


【解决方案1】:

以下工作(尽管我会重新考虑在此处使用 System.Timers.Timer,正如@JeroenvanLangen 评论的那样),这只是您将Console.Title = 放在哪里

  class Program
  {
    public static int current_hour = 0;
    public static int current_minute = 0;
    public static int current_seconds = 0;
   
    public static void Timer_Elapsed(object sender, ElapsedEventArgs e)
    {
      current_seconds++;
      if (current_seconds >= 60)
      {
        current_minute++;
        current_seconds = 0;
        if (current_minute >= 60)
        {
          current_minute = 0;
          current_hour++;
        }
      }
      Console.Title = $"Elapsed time: {current_hour:00}:{current_minute:00}:{current_seconds:00}";    
    }
    
    static void Main(string[] args)
    {
      System.Timers.Timer clockcount = new System.Timers.Timer();
      clockcount.AutoReset = true;
      clockcount.Interval = 1000;
      clockcount.Elapsed += Timer_Elapsed;
      clockcount.Enabled = true;
      clockcount.Start();
      while(Console.ReadKey().KeyChar != 'x') 
        Thread.Sleep(500);
    }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-02
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多