C# Timers

There are three kinds of timers in .Net but it’s not always obvious when to use which one.  Here’s some sample code of each, and then later on a table from the MSDN website that summarizes the differences.

// Runs on the UI thread
// Will not raise events if UI is unable to process them
private void RunTimer()
{
   //Create System.Windows.Forms.Timer
   System.Windows.Forms.Timer myTimer =
         new System.Windows.Forms.Timer();
   //Set the timer interval in milliseconds
   myTimer.Interval = 2000;
   myTimer.Tick += new EventHandler(myTimerTick);
   myTimer.Start();
   //Run the timer for 10 seconds
   System.Threading.Thread.Sleep(10000);
   myTimer.Stop();
}

void myTimer_Tick(object sender, EventArgs e)
{
   //Do something useful here
   System.Threading.Thread.Sleep(1000);
}
//Thread-safe
//Will run Elapsed event on a thread from thread pool
private void RunTimer2()
{
  //Create System.Timers.Timer
  System.Timers.Timer myTimer =
    new System.Timers.Timer();

  //Set the timer interval in milliseconds
  myTimer.Interval = 2000;
  //What to do when the timer expires
  myTimer.Elapsed +=
  new System.Timers.ElapsedEventHandler(myTimer_Elapsed);

  myTimer.Start();
}

void myTimer_Elapsed(object sender,
   System.Timers.ElapsedEventArgs e)
{
   //The timer has expired - do something
}
//Not thread safe - but you can use it in a
//thread safe way
//Runs on a worker thread
private void RunTimer3()
{
  System.Threading.Timer myTimer =
  new System.Threading.Timer(TimerCallback, null,
     5000, System.Threading.Timeout.Infinite);
}
private void TimerCallback(object o)
{
   //The timer has expired - do something
}

System.Windows.Forms System.Timers System.Threading
Timer event runs on what thread? UI thread UI or worker thread Worker thread
Instances are thread safe? No Yes No
Familiar/intuitive object model? Yes Yes No
Requires Windows Forms? Yes No No
Metronome-quality beat? No Yes* Yes*
Timer event supports state object? No No Yes
Initial timer event can be scheduled? No No Yes
Class supports inheritance? Yes Yes No
* Depending on the availability of system resources (for example, worker threads)

Comments are closed.