See Also: Timer Members
A System.Threading.TimerCallback delegate is used to specify the methods associated with a Timer . The methods do not execute in the thread that created the timer; they execute in a separate thread that is automatically allocated by the system. The timer delegate is specified when the timer is constructed, and cannot be changed.
When creating a timer, the application specifies an amount of time to wait before the first invocation of the delegate methods (due time), and an amount of time to wait between subsequent invocations (period). A timer invokes its methods once when its due time elapses, and invokes its methods once per period thereafter. These values can be changed, or the timer disabled using the Timer.Change(int, int) method.
When a timer is no longer needed, use the Timer.Dispose(WaitHandle) method to free the resources held by the timer.
The following example demonstrates the features of the System.Threading.Timer class.
C# Example
using System;
using System.Threading;
class TimerExampleState {
public int counter = 0;
public Timer tmr;
}
class App {
public static void Main() {
TimerExampleState s = new TimerExampleState();
// Create the delegate that invokes methods for the timer.
TimerCallback timerDelegate = new TimerCallback(CheckStatus);
// Create a timer that waits one second, then invokes every second.
Timer timer = new Timer(timerDelegate, s, 1000, 1000);
// Keep a handle to the timer, so it can be disposed.
s.tmr = timer;
// The main thread does nothing until the timer is disposed.
while (s.tmr != null)
Thread.Sleep(0);
Console.WriteLine("Timer example done.");
}
// The following method is called by the timer's delegate.
static void CheckStatus(Object state) {
TimerExampleState s = (TimerExampleState) state;
s.counter++;
Console.WriteLine("{0} Checking Status {1}.",DateTime.Now.TimeOfDay, s.counter);
if (s.counter == 5) {
// Shorten the period. Wait 10 seconds to restart the timer.
(s.tmr).Change(10000,100);
Console.WriteLine("changed...");
}
if (s.counter == 10) {
Console.WriteLine("disposing of timer...");
s.tmr.Dispose();
s.tmr = null;
}
}
}
An example of some output is
10:51:40.5809015 Checking Status 1.The exact timings returned by this example will vary.