Reader Level:

Timer class in Threading

By Akshay Teotia on Dec 20, 2011
The Timer class provides a way to execute methods at specified intervals and it cannot be inherited.


System.Threading.Timer Class

The Timer class (in the System.Threading namespace) is effective to periodically run a task on a separate thread. It provides a way to execute methods at specified intervals. This class cannot be inherited.

This class is particularly useful for developing console applications, where the System.Windows.Forms.Timer class is inaccessible. Thus, we can use a thread timer to back up files, or to ensure the consistency of a database.

When creating a timer object, you would need to assess the time to wait before the first invocation of the delegate method ( dueTime ) and the time to wait between succeeding invocations ( period ). A timer invokes its methods when its due time elapses, and invokes its methods once per period thereafter. You can use the Change method of the Timer class to change these values, or disable the timer. You can use the Dispose method of the Timer class to free the resources when a timer is no longer needed.

The TimerCallback delegate specifies the methods associated with a Timer object and handles its state. It invokes its methods once after the dueTime elapses and continues invoking its methods once per period until the Dispose method is called. The system automatically allocates a separate thread on which to execute the methods associated with the delegate.

Assembly : Mscorlib.dll

Namespace : System.Threading


Provides a mechanism for executing methods at specified intervals. This class cannot be inherited.

C# Syntax :

    public sealed class Timer : MarshalByRefObject, IDisposable

Let us see a small piece of code where we would create a Timer object and use it. We will first need to create a TimerCallback delegate with a method that would be called. Next we will need to create a state object (if one is needed) that contains application specific info relevant to the methods invoked by the delegate. To put things simple, we a null reference here. We will then instantiate a Timer object (where we the delegate, state object and two more parameters that define the dueTime and period of the Timer ). We will use the Change method to change the Timer object settings. Finally, we will kill the Timer object by calling the Dispose method.

To run following code we need.

  •  To copy this code into Notepad and save it into .cs (for example akshay.cs)
  • Compile this program with the following command line C:>csc akshay.cs
  • Run this program with the following command line C:>akshay

using System;
using System.Windows.Forms;
using System.Threading;
namespace nsDelegates
    public class ThrdTime
        static int countdown = 10;
        static System.Threading.Timer timer;
        static public void Main ()
// Create the timer callback delegate.
System.Threading.TimerCallback cb = new System.Threading.
TimerCallback (ProcessTimerEvent);

// Create the object for the timer.
            clsTime time = new clsTime ();
// Create the timer. It is autostart, so creating the timer will start it.
            timer = new System.Threading.Timer (cb, time, 40001000);
// Blessed are those who wait.
            MessageBox.Show ("Waiting for countdown""Text");
// Callback method for the timer. The only parameter is the object you
// ed when you created the timer object.
        private static void ProcessTimerEvent (object obj)
// If countdown is complete, exit the program.
            if (countdown == 0)
                timer.Dispose ();
                Environment.Exit (0);
            string str = "";
// Cast the obj argument to clsTime.
            if (obj is clsTime)
                clsTime time = (clsTime) obj;
                str = time.GetTimeString ();
            str += "\r\nCountdown = " + countdown;
            MessageBox.Show (str, "Timer Thread");
// Define a class to use as the object argument for the timer.
    class clsTime
        public string GetTimeString ()
            string str = DateTime.Now.ToString ();
            int index = str.IndexOf(" ");
            return (str.Substring (index + 1));



Timer properties


MSDN: this indicates "whether the Timer should raise the Elapsed event each time the specified interval elapses or only after the first time it elapses." That means if you want a recurring timer, leave this as true.


"Whether the Timer should raise the Elapsed event." You must set this to true if you want your timer to do anything.


This indicates "the time, in milliseconds, between raisings of the Elapsed event. The default is 100 milliseconds." You will almost certainly want to make this interval longer than the default. For example, for 30 seconds, use 30000 as the Interval.


This does the same thing as setting Enabled to true. I am not certain why we need this duplicate method.


This does the same thing as setting Enabled to false. See the Timer.Start method shown previously.

Timer.Elapsed Event

This is the event that is invoked each time the Interval of the Timer has ed. You must specify this function in your code. To add the event, you can press tab twice after typing " timer.Elapsed +=".

Dispose and Disposed

Timers allocate system resources, so if you are creating a lot of them, make sure to Dispose them. This gets complicated fast. I suggest just using a single static timer.



Custom Software Development
MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.

Trending up