1

我制作了一个计时器,可以每秒刷新 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();
4

1 回答 1

0

以下作品(尽管我会重新考虑使用 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);
    }
  }
于 2021-10-12T09:03:38.020 回答