Elapsed time chronometer doesn't get refreshed constantly

43 views Asked by At

i made a chronometer that refresh the time on the Console.Title every second, but it doesn't work, it never get refreshed. It's always in 00:00:00. How to do for that get refreshed every second? Thanks!

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')}";

Here is the function.

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();
}

And here's the code that runs the elapsed time when the user press Start on the console

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

There are 1 answers

0
AlanK On

The following works (although I'd reconsider using System.Timers.Timer here as @JeroenvanLangen commented), it's just about where you put that 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);
    }
  }