How do you add a timer to a C# console application

That’s very nice, however in order to simulate some time passing we need to run a command that takes some time and that’s very clear in second example.

However, the style of using a for loop to do some functionality forever takes a lot of device resources and instead we can use the Garbage Collector to do some thing like that.

We can see this modification in the code from the same book CLR Via C# Third Ed.

using System;
using System.Threading;

public static class Program 
{
   private Timer _timer = null;
   public static void Main() 
   {
      // Create a Timer object that knows to call our TimerCallback
      // method once every 2000 milliseconds.
      _timer = new Timer(TimerCallback, null, 0, 2000);
      // Wait for the user to hit <Enter>
      Console.ReadLine();
   }

   private static void TimerCallback(Object o) 
   {
      // Display the date/time when this method got called.
      Console.WriteLine("In TimerCallback: " + DateTime.Now);
   }
}

Leave a Comment