Reader Level:
ARTICLE

Timer class in Threading

Posted by Akshay Teotia Articles | Multithreading in C# December 20, 2011
The Timer class provides a way to execute methods at specified intervals and it cannot be inherited.
  • 0
  • 0
  • 38005
Download Files:
 

Introduction

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

Summary

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 pass a null reference here. We will then instantiate a Timer object (where we pass 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
// passed when you created the timer object.
        private static void ProcessTimerEvent (object obj)
        {
            --countdown;
// 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));
        }
    }
}

Output:

timerclass.jpg

Timer properties

Timer.AutoReset

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.

Timer.Enabled

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

Timer.Interval

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.

Timer.Start

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

Timer.Stop

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 passed. 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.

COMMENT USING

Trending up