Here we will introduce the C # checkstatus () method and call the timer. Dispose () method to delete the timer object. The main thread jumps out of the loop and terminates the program.
C # is a common language. Here we mainly introduce the C # checkstatus () method, including setting a timer and regularly executing user-specified functions.
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.
- 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, in milliseconds,
0 indicates that the timer is started immediately;
- // The fourth parameter: the timer interval. After the timer starts,
Timercallback indicates that the method will be called once in milliseconds.
The specified Timeout. Infinite can disable periodic termination.
Timer. Change () method: Modify the timer settings. (This is a method to overload the parameter type) Example: timer. Change );
Example of a Timer Program:
- 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 call the C # 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.