Wednesday, June 27, 2007

Threads in .NET

Threads in .NET :

A common use of threads is for all kinds of periodical updates.

.NET offers three different ways:


Windows timers with the

System.WinForms.Timer class


Periodical delegate calling with

System.Threading.Timer class


Exact timing with the

System.Timers.Timer class



System.WinForms.Timer class :


For inexact timing we use the window timer. Events raised from the window timer go through the message pump (together with all mouse events and UI update messages) so they are never exact. The simplest way for creating a WinForms.Timer is by adding a Timer control onto a form and creating an event handler using the control's properties. We use the Interval property for setting the number of milliseconds between timer ticks and the Start method to start ticking and Stop to stop ticking.

System.Threading.Timer

class :
The System.Threading.Timer class is a new waiting thread in the thread pool that periodically calls supplied delegates. To use it you must perform several steps:


Create state object which will carry information to the delegate


Create TimerCallback delegate with a method to be called. You can use static or instance methods.


Create a Timer object with time to wait before first call and periods between successive calls (as names of this two parameters suggests, first parameter should be lifetime of this timer object, but it just don't work that way)


Change the Timer object settings with the Change method (same remark on parameters apply)


Kill the Timer object with the Dispose method

System.Timers.Timer

class :

The final timing options come from the System.Timers.Timer class. It represents server-based timer ticks for maximum accuracy. Ticks are generated outside of our process and can be used for watch-dog control. In the same System.Timers namespace you can find the Schedule class which gives you the ability to schedule timer events fired at longer time intervals.

System.Timers.Timer class is the most complete solution for all time fired events. It gives you the most precise control and timing and is surprisingly simple to use.


Create the Timer object. You can a use constructor with interval setting.


Add your event handler (delegate) to the Tick event


Set the Interval property to the desired number of milliseconds (default value is 100 ms)


Set the AutoReset property to false if you want the event to be raised only once (default is true – repetitive raising)


Start the ticking with a call to the Start() method, or by setting Enabled property to true.


Stop the ticking with call to the Stop() method or by setting the Enabled property to false.

No comments: