Timer class: Set a timer to execute the user-specified function on a timed basis. after the timer starts, a new thread is automatically created to execute the user-specified function. Initialize a Timer object:Timer timer = new Timer (timerdelegate, s,1000, +);///First parameter: Specifies the TimerCallback delegate, indicating the method to be executed;///second parameter: An object containing the information to be used by the callback method, or a null reference;///Third parameter: Delay time-the time at which the timing starts, in milliseconds, specified as "0" to start the timer immediately;//Fourth parameter: Timer Interval--After the start of the timer, the method represented by TimerCallback will be called once for such a long period of time, and the unit is also milliseconds. Specifies that timeout.infinite can disable periodic termination. Timer.change () method: Modify the Timer settings. (This is a method of parameter type overloading)Use Example: Timer. Change (1000,2000); example of a program for the Timer class (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 proxy object TimerCallback, the agent will be called periodically TimerCallback timerdelegate = new TimerCallback (checkstatus); //Create a timer with a time interval of 1s Timer timer = New timer (timerdelegate, S,+, +); S.TMR = timer; //The main thread stops to wait for the timer object to terminate While (s.tmr! = null) Thread.Sleep (0); Console.WriteLine ("Timer example done.") );console.readline (); } //The following are methods that are called periodically 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) { //Using the Change method changes the time interval (S.TMR). Change (10000,+); Console.WriteLine ("changed "); } if(s.counter = = ten) {Console.WriteLine ("Disposing of the timer ");s.tmr.dispose ();S.TMR = null; } } }}The program first creates a timer, which begins to call the CheckStatus () method every 1 seconds after the creation of 1 seconds, and after 5 calls, modifies the time interval to 2 seconds in the CheckStatus () method, and specifies to start again after 10 seconds. When the count reaches 10 times, the call Timer.dispose () method removes the timer object, and the main thread jumps out of the loop and terminates the program.
C # multithreaded Learning (v) multi-threaded automatic management (timers)