Timers in .NET
I was researching timers the other day and realized that there are three variations in the .NET Framework.

The three types of timers are explained below.
1 – System.Timers.Timer
The System.Timers.Timer class timer is considered a server-based timer that was designed and optimized for use in multithreaded environments. It can be accessed safely from multiple threads.
C# Program
using System; using System.Timers; public class Program { private static System.Timers.Timer testTimer; public static void Main(string[] args) { testTimer = new System.Timers.Timer(5000); // 5 seconds testTimer.Elapsed += new ElapsedEventHandler(OnTimerElapsed); testTimer.Interval = 5000; testTimer.Enabled = true; Console.WriteLine("Press the enter key to stop the timer"); Console.ReadLine(); } private static void OnTimerElapsed(object source, ElapsedEventArgs e) { Console.WriteLine("Timer elapsed at {0}", e.SignalTime); } }
Output

–
2 – System.Threading.Timer
The System.Threading.Timer class timer uses a TimerCallBack Delegate to specify the associated methods. The methods do not execute in the thread that created the timer; they execute in a separate thread that is automatically allocated by the system.
C# Program
using System; using System.Threading; class Program { static void Main() { AutoResetEvent reset = new AutoResetEvent(false); StatusChecker status = new StatusChecker(5); // Invoke methods for the timer via a Delegate TimerCallback timerDelegate = new TimerCallback(status.CheckStatus); // Create a timer that signals the delegate to invoke // Check status after one second, and then every 1/4 second Console.WriteLine("{0} Creating the timer.\n", DateTime.Now.ToString("h:mm:ss.fff")); Timer stateTimer = new Timer(timerDelegate, reset, 1000, 250); // When the auto reset executes, change to every 1/2 second reset.WaitOne(5000, false); stateTimer.Change(0, 500); Console.WriteLine("\nChanging the timer period.\n"); reset.WaitOne(5000, false); stateTimer.Dispose(); Console.WriteLine("\nDestroying the timer."); } } class StatusChecker { int invokeCount, maxCount; public StatusChecker(int count) { invokeCount = 0; maxCount = count; } // This method is called by the timer delegate. public void CheckStatus(Object stateInfo) { AutoResetEvent autoEvent = (AutoResetEvent)stateInfo; Console.WriteLine("{0} Checking status {1,2}.", DateTime.Now.ToString("h:mm:ss.fff"), (++invokeCount).ToString()); if (invokeCount == maxCount) { // Reset the counter and signal Main. invokeCount = 0; autoEvent.Set(); } } }
Output

–
3 – Windows.Forms.Timer
The Windows.Forms.Timer class works synchronously with the Windows Form, so that it will not interrupt any operations. It initializes on the UI thread.
C# Program
using System; using System.Windows.Forms; namespace WindowsFormsTimer { public class Class1 { static System.Windows.Forms.Timer theTimer = new System.Windows.Forms.Timer(); static int alarmCounter = 1; static bool exitFlag = false; // Timer raised method private static void TimerEventProcessor(Object myObject, EventArgs myEventArgs) { theTimer.Stop(); // Displays a message box asking whether to continue to run the timer if (MessageBox.Show("Continue running?", "Count is " + alarmCounter, MessageBoxButtons.YesNo) == DialogResult.Yes) { // Restarts the timer and increments the counter alarmCounter += 1; theTimer.Enabled = true; } else { // Stops the timer exitFlag = true; } } public static int Main() { //Adds the event and the event handler for the method that will //process the timer event to the timer theTimer.Tick += new EventHandler(TimerEventProcessor); // Sets the timer interval to 5 seconds theTimer.Interval = 2000; theTimer.Start(); // Runs the timer, and raises the event while (exitFlag == false) { // Processes all the events in the queue Application.DoEvents(); } return 0; } } }
Output

–
There are three choices for timers in .NET. It just depends on what you want to do.
–
More Information
- Comparing the Timer Classes in the .NET Framework Class Library
- System.Timers.Timer vs System.Threading.Timer
- Working with Timer Control in VB.NET
–
Until next time…
^..^
Posted on November 6, 2009, in .NET General, C#. Bookmark the permalink. 4 Comments.







hhhmmm I initially read your blog post cause I was looking for the differences in why/when to use the different timers. Unfortunately just as I get to the “…depends on what you want to do” you end the post. DOH! Can you expand on this please?
@phenry9999 – I meant this to be a complete beginner post. I am researching the why/when and was planning on doing another post…hopefully in the near future. There is not a ton of info on the differences.
Thanks for the response. Very cool, I subscribed to your rss feed, can’t wait for the update. Thanks for looking into this (I hope :>HAHA). Have a good day!
Pingback: Dew Drop – November 7, 2009 | Alvin Ashcraft's Morning Dew