Timer class: sets a Timer to regularly execute user-specified functions.
After the timer starts, the system automatically creates a new thread to execute the user-specified function.
Initialize a Timer object:
Timer timer = new Timer (timerDelegate, s, 1000,100 0 );
// The first parameter: Specifies the TimerCallback delegate, indicating the method to be executed;
// The second parameter: an object that contains the information to be used by the callback method, or an empty reference;
// The third parameter: Delay Time-the time from which the timer starts, in milliseconds. If it is set to "0", the timer is started immediately;
// Fourth parameter: time interval of the timer-after the timer starts, the method represented by TimerCallback will be called every so long time, in milliseconds. The specified Timeout. Infinite can disable periodic termination.
Timer. Change () method: Modify the Timer settings. (This is a method to overload parameter types)
Example: timer. Change );
Example of a Timer class Program (Source: MSDN ):
Using System;
Using System. Threading;
Namespace ThreadExample
{
Class TimerExampleState
{
Public int counter = 0;
Public Timer tmr;
}
Class App
{
Public static void Main ()
{
TimerExampleState s = new TimerExampleState ();
// Create the proxy object TimerCallback, which will be called regularly
TimerCallback timerDelegate = new TimerCallback (CheckStatus );
// Create a timer with an interval of 1 s
Timer timer = new Timer (timerDelegate, s, 1000,100 0 );
S. tmr = timer;
// The main thread stops and waits for the termination of the Timer object
While (s. tmr! = Null)
Thread. Sleep (0 );
Console. WriteLine ("Timer example done .");
Console. ReadLine ();
}
// The following method is called regularly
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)
{
// The Change method is used to Change the time interval.
(S. tmr). Change (random, 2000 );
Console. WriteLine ("changed ");
}
If (s. counter = 10)
{
Console. WriteLine ("disposing of timer ");
S. tmr. Dispose ();
S. tmr = null;
}
}
}
}
The program first creates a timer, which will start to call the CheckStatus () method once every one second after the creation of 1 second. After five calls () the time interval is modified to 2 seconds, and the task starts again after 10 seconds. When the Count reaches 10 times, the Timer object is deleted by calling the timer. Dispose () method, and the main thread jumps out of the loop and terminates the program.