In many situations we require to call the particular method in a particular time interval. For example you have a service which seeks for emails by calling email server, in this type of situation Timer is useful to call email server in particular interval of time.
Today we discuss about TimerCallback delegate and Timer in C#. Open Visual Studio => Create Console Application and add below code.
using System;
using System.Threading;
namespace CSharpTimer
{
class Program
{
static void Main(string[] args)
{
TimerCallback delTime = new TimerCallback(DisplayTime);
Timer t = new Timer(delTime, null, 0, 1000);
Console.ReadLine();
}
static void DisplayTime(object state)
{
Console.WriteLine("Current Time is: {0}",
DateTime.Now.ToLongTimeString());
}
}
}
As shown above we have DisplayTime() method which displays current time. Created the object delTime for TimerCallback delegate by passing DisplayTime() method. Create the object for Timer class which takes TimerCallback type, inputs to called method(here we are passing null that means no inputs to DisplayTime() method), due time and interval of time.
Execute the above program, the output is as shown below.
As shown above, DisplayTime() method is calling for every one second.