Timers
The easiest way to execute a method periodically is using a timer.
There are three different Timer classes been provided.
- System.Threading.Timer
- System.Timers.Timer
- System.Windows.Forms.Timer
System.Threading.Timer
The threading timer takes advantage of the thread pool, Allowing Many Timers To Be Created without the overhead of many threads.
Timer is a fairly simple class, with a constructor and just two methods (a delight for minimalists, as well as book authors!).
| class Program { static void { Timer tmr = new Timer(Tick, "tick...", 5000, 1000); Console.ReadLine(); tmr.Dispose(); } static void Tick(object data) { Console.WriteLine(data); // Writes "tick..." } } Output – Here timer calls the Tick method which writes "tick..." after 5 seconds have elapsed, then every second after that – until the user presses Enter: |
System.Timers.Timer
This simply wraps System.Threading.Timer, providing additional convenience while Using The Same Thread Pool – and the identical underlying engine.
Here's a summary of its added features:
- A Component implementation, allowing it to be sited in the Visual Studio Designer
- An Interval property instead of a Change method
- An Elapsed event instead of a callback delegate
- An Enabled property to start and pause the timer (its default value being false)
- Start and Stop methods in case you're confused by Enabled
- An AutoReset flag for indicating a recurring event (default value true)
| public partial class Form1 : Form { private System.Timers.Timer timer = null; public Form1() { InitializeComponent(); int timerPeriod = 30000; timer = new System.Timers.Timer(timerPeriod); timer.Elapsed += new ElapsedEventHandler(this.ticker_Elapsed); label1.Text = "Not Started ..."; } private void button1_Click(object sender, EventArgs e) { timer.Start(); label1.Text = "Started ..."; } private void ticker_Elapsed(object sender, ElapsedEventArgs e) { using (SqlConnection cnx = ConnectionPool.GetConnection()) { // Code Here } } private void button2_Click(object sender, EventArgs e) { timer.Stop(); label1.Text = "Stopped ..."; } } |
System.Windows.Forms.Timer
- While similar to System.Timers.Timer in its interface, it's radically different in the functional sense.
- A Windows Forms timer Does Not Use The Thread Pool, instead firing its "Tick" event always on the same thread that originally created the timer.
- Assuming this is the main thread – also responsible for instantiating all the forms and controls in the Windows Forms application – the timer's event handler is then able to interact with the forms and controls without violating thread-safety – or the impositions of apartment-threading.
- Control.Invoke is not required.
- The Windows timer is, in effect, a single-threaded timer.
Note –
There's an equivalent single-threaded timer for WPF, called DispatcherTimer.
Hope this helps.
Thanks & Regards,
Arun Manglick || Senior Tech Lead
No comments:
Post a Comment