How to create a timer in C#
To create a timer in C#, you have to use the Timer class, which allows you to execute methods at a specified interval. Below is a simple example of a timer using C#.
using System;using System.Threading;public static class Program {public static void Main() {Timer t = new Timer(TimerCallback, null, 0, 1000);Console.ReadLine();}private static void TimerCallback(Object o) {Console.WriteLine("In TimerCallback: " + DateTime.Now);}}
-
Uses the
System.Threadingnamespace, which allows you access various classes and interfaces that enable multi-threaded programming, like theTimerclass (Line 2). -
Creates a
Timerobject that will call theTimerCallbackfunction every 1000 milliseconds. Thenullvalue is for thestateparameter, which allows you to pass any information to be used in the callback method. The0is for thedueTimevariable, which is the time of delay before the callback is called (Line 7). -
Waits for the user to hit
Enter, which will stop the timer (Line 8). -
Creates the function
TimerCallback, which will be called every 1000 milliseconds from theTimerobject. Objectois passed in, since theTimerCallbackfunction requires an object parameter, even if you don’t use it (Line 11). -
Logs the time in the console every second, or 1000 milliseconds (Line 12).
Free Resources