myTimer.Interval- sets how often the "Tick" event is called (in milliseconds)
myTimer.Enabled- boolean value that sets the timer to be enabled / disabled
myTimer.Start()- Starts the timer.
myTimer.Stop()- Stops the timer.
If using Visual Studio, Timers can be added as a control directly to your form from the toolbox.
Assigning the "Tick" event handler to a Timer
All actions performed in a timer are handled in the "Tick" event.
Creating an Instance of a Timer
Timers are used to perform tasks at specific intervals of time (Do X every Y seconds) Below is an example of creating a new instance of a Timer.
NOTE: This applies to Timers using WinForms. If using WPF, you may want to look into
Example: Using a Timer to perform a simple countdown.
And so on...
System.Threading.Timer - Simplest multithreaded timer. Contains two methods and one constructor.
Example: A timer calls the DataWrite method, which writes "multithread executed..." after five seconds have elapsed, and then every second after that until the user presses Enter:
Note : Will post a separate section for disposing multithreaded timers.
Change - This method can be called when you would like change the timer interval.
Timeout.Infinite - If you want to fire just once. Specify this in the last argument of the constructor.
System.Timers - Another timer class provided by .NET Framework. It wraps the
IComponent- Allowing it to be sited in the Visual Studio’s Designer’s component tray
Intervalproperty instead of a
eventinstead of a callback
Enabledproperty to start and stop the timer (
default value = false)
Stopmethods in case if you get confused by
Enabledproperty (above point)
AutoReset- for indicating a recurring event (
default value = true)
BeginInvokemethods for safely calling methods on WPF elements and Windows Forms controls
Example representing all the above features:
Multithreaded timers - use the thread pool to allow a few threads to serve many
timers. It means that callback method or
Elapsed event may trigger on a different
thread each time it is called.
Elapsed - this event always fires on time—regardless of whether the previous
Elapsed event finished executing. Because of this, callbacks or event handlers must be thread-safe.
The accuracy of multithreaded timers depends on the OS, and is typically
in the 10–20 ms.
interop - when ever you need greater accuracy use this and call the Windows multimedia timer. This has accuracy down to 1 ms and it is defined in
timeBeginPeriod - Call this first to inform OS that you need high timing accuracy
timeSetEvent - call this after
timeBeginPeriod to start a multimedia timer.
timeKillEvent - call this when you are done, this stops the timer
timeEndPeriod - Call this to inform the OS that you no longer need high timing accuracy.
You can find complete examples on the Internet that use the multimedia timer by searching for the keywords