Timer class:
Set a timer to regularly execute the user-specified function. After the timer starts, the system automatically creates a new thread to execute the user-specified function.
UsingSystem;
UsingSystem. Threading;
NamespaceThreadexample
{
ClassTimerexamplestate
{
Public IntCounter = 0;
PublicTimer TMR;
}
ClassApp
{
Public Static VoidMain ()
{
Timerexamplestate S =NewTimerexamplestate ();
// Create a proxy object system. Threading. timercallback, which will be called regularly
Timercallback timerdelegate =NewTimercallback (checkstatus );
// Create a timer with a 1 s Interval
// 1st parameters: Specifies the timercallback delegate, indicating the method to be executed;
// 2nd parameters: an object that contains the information to be used by the callback method, or an empty reference;
// 3rd parameters: Delay Time-the time from which the timer starts, in milliseconds. If it is set to "0", the timer is started immediately;
// 4th parameters: time interval of the timer. After the timer starts, the method represented by timercallback is called once every so long.
Timer timer =NewTimer (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 ();
}
/// <Summary>
/// The following method is called regularly
/// </Summary>
/// <Param name = "state"> </param>
Static VoidCheckstatus (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 to 2 seconds, and then wait for 10 seconds.
(S. TMR). Change (10000,200 0 );
Console. writeline ("Changed");
}
If(S. Counter = 10)
{
Console. writeline ("Disposing of timer! ");
S. TMr. Dispose ();
S. TMR =Null;
}
}
}
}
Program first creates a timer, which calls the checkstatus () method once every one second after being created. After five calls, the interval in the checkstatus () method is changed to 2 seconds, and the interval 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.