Suppose you have an application to display the stock index. Rather than relying on the “refresh” button, you might want to refresh itself in a specific time interval. “System.Threading.Timer” can be used for this scenario.
1. Timer Class
The “System.Threading.Timer” class has the following constructors:
public sealed class Timer : IDisposable { public Timer(TimerCallback callback); public Timer(TimerCallback callback, Object state, int dueTime, int period); public Timer(TimerCallback callback, Object state, long dueTime, long period); public Timer(TimerCallback callback, Object state, TimeSpan dueTime, TimeSpan period); }
- state : An object containing information to be used by the callback method, or null.
- dueTime : the delay time to start the timer, in milliseconds. Specify zero (0) to start the timer immediately
- period : the interval time, in milliseconds.
You need to specify “Timeout.Infinite” to disable duetime or period.
2. TimerCallback Delegate
You need to provide a method to run when a timer is enabled.
public delegate void TimerCallback(Object state);
3. One-Time Timer
You can create a one-time timer by setting the “period” parameter to “Timeout.Infinite“.
- dueTime : delay time
- period : Timeout.Infinite
public class RangeParameter { public int Start { get; set; } public int End { get; set; } } public static class TimerTest { public static void TestOneTimeTimer() { RangeParameter range = new RangeParameter { Start = 10, End = 50 }; Timer oneTimeTimer = new Timer(state => { RangeParameter data = state as RangeParameter; for (int i = data.Start; i < data.End; i++) { Console.Write(i + " "); Thread.Sleep(1); } }, range, 1000, // after 1 second Timeout.Infinite // no interval ); Console.WriteLine("Timer has not been triggered"); Thread.Sleep(2000); Console.WriteLine("Timer has been triggered"); } }
4. Periodic Timer
Now let’s create a timer that is triggered periodically.
- dueTime : 0
- period : time in milliseconds
public static void Test2() { RangeParameter range = new RangeParameter { Start = 1, End = 5 }; using (Timer oneTimeTimer = new Timer(state => { RangeParameter data = state as RangeParameter; for (int i = data.Start; i < data.End; i++) { Console.Write(i + " "); Thread.Sleep(1); } }, range, 0, 1000 // every 1 second ) ) { Console.WriteLine("Timer has not been triggered"); Thread.Sleep(5000); Console.WriteLine("Timer has been triggered many times"); } Thread.Sleep(5000); Console.WriteLine("Timer has stopped"); }