Call method after specific time interval C#

Hello friends, We have already explain regarding Right Join in Alert from code behind asp.net,required field validator in asp.net,Difference between RegisterClientScriptBlock and RegisterStartupScript asp.netDifference between ref and out parameters. Today I am going to explain regarding Call method after specific time interval C#.

Lets say I want to print some message after each 1 second on console, please refer below screenshot for expected output

Call method after specific time interval C-Sharp
Call method after specific time interval C-Sharp

We need to use “System.Timers.Timer” for set time interval for achieving above task. and call method in “ElapsedEventHandler” as shown in below sample code.

Sample code:

static void Main(string[] args)
{
    System.Timers.Timer time = new System.Timers.Timer();
    time.Interval = 1000;
    time.Elapsed += new System.Timers.ElapsedEventHandler(testMethod);
    time.Start();
    testMethod(time, null);
    Console.ReadKey();
}

private static void testMethod(object sender, System.Timers.ElapsedEventArgs e)
{
            
    Console.WriteLine("Hello World on Date-Time:" + DateTime.Now);
}

Download Demo code of Call method after specific time interval C#

4 comments

Leave a Reply