Execute an operation periodically on thread pool using Timer Construct

How to use Timer and execute a method periodically


Category: Multithreading Tags: C#


Introduction

        Sometimes we need to run an operation periodically, there are many ways to do that but here I am going to show you how to do that on thread pool using Timer.

Implementation

        See code below:
static void TimerOperation(DateTime start)
{
    TimeSpan elapsed = DateTime.Now - start;
    Console.WriteLine("It has been {0} seconds after {1}. This Thread Pool Id: {2}", elapsed, start, Thread.CurrentThread.ManagedThreadId);
}
Above we created a TimerOperation method which prints elapsed time and thread pool id. Now we need to call this method periodically.
static Timer timer;
static void Main(string[] args)
{
    Console.WriteLine("Press 'Enter' to stop execution...");
    DateTime start = DateTime.Now;
    timer = new Timer(_ => TimerOperation(start), null, 1000, 2000);
    Thread.Sleep(5000);
    timer.Change(500, 100);
    Console.ReadLine();
    timer.Dispose();
}
Above we created object of timer in Main method, 1000ms is due time means after 1 second thread will start execution and 2000 is period in that interval timer will execute TimerOperation method periodically. Change method can change values of due time and period and Dispose is used to dispose timer and stop execution. We can use Timeout.Infinite instead of period if we want TimerOperation to be executed only once. Output will be like:

Press 'Enter' to stop execution...
It has been 00:00:01.0066893 seconds after 3/16/2017 2:50:58 PM. This Thread Pool Id: 12
It has been 00:00:03.0125104 seconds after 3/16/2017 2:50:58 PM. This Thread Pool Id: 12
It has been 00:00:05.5225906 seconds after 3/16/2017 2:50:58 PM. This Thread Pool Id: 12
….

Like 0 People
Last modified on 15 June 2018
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 165
Questions: 16
Given Best Solutions: 16 *

Comments:

No Comments Yet

You are not loggedin, please login or signup to add comments:

Existing User

Login via:

New User



x