Timer class: Set up a timer that executes the user-specified function at timed intervals.
When the timer is started, the system will automatically create a new thread that executes the user-specified function.
Initializes a Timer object:
Timer timer = new Timer (timerdelegate, s,1000, 1000);
First parameter: Specifies a TimerCallback delegate that represents the method to be executed;
Second parameter: An object that contains the information to be used by the callback method, or a null reference;
Third parameter: Delay time-the time from which the timing begins is now, in milliseconds, and specifies "0" to start the timer immediately;
Fourth parameter: Timer Interval--After the timer starts, every so long time, the method represented by TimerCallback will be called once, in milliseconds. Specifies that timeout.infinite can be disabled for periodic termination.
Timer.change () Method: Modify the Timer settings. (This is a method of parameter type overloading)
Use Example: Timer. Change (1000,2000);
Program Sample for Timer class (Source: MSDN):
The
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 proxy object TimerCallback, which will be called periodically
TimerCallback timerdelegate = new TimerCallback (checkstatus);
//Create a time between 1s timer
Timer timer = new Timer (timerdelegate, s,1000, 1000);
S.TMR = timer;
//main thread stop waiting for timer object to terminate
while . TMR!= null)
Thread.Sleep (0);
Console.WriteLine ("Timer example done.");
Console.ReadLine ();
}
//Below is the method that is called periodically
static void CheckStatus (Object state)
{
Timerexamplestate s = (Timerexampl Estate) state;
s.counter++;
Console.WriteLine ("{0} Checking Status {1}.", DateTime.Now.TimeOfDay, S.counter);
if (s.counter = 5)
{
//changes the time interval using the Change method
(S.TMR). Change (10000,2000);
Console.WriteLine ("Changed");
}
if (s.counter = =)
{
Console.WriteLine ("Disposing of Timer");
S.tmr.dispose ();
S.TMR = null;}
}
}
The program first creates a timer that starts calling the CheckStatus () method every 1 seconds after creating 1 seconds, modifies the interval to 2 seconds in the CheckStatus () method after 5 times, and specifies to start again after 10 seconds. When the count reaches 10 times, the calling Timer.dispose () method deletes the timer object, and the main thread jumps out of the loop and terminates the program.
Posted