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 current time from the start time of the timer, in milliseconds. 0" Indicates that 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 );
Timer classProgramExample (Source: msdn ):
Code
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 a time interval of 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 (10000,200 0 );
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.