I. About this article
This article implements the timertest class, which can simulate a timer and execute an event at a specified interval.
Ii. timertest class
// Timer class timertest {// thread name string _ threadname; Public String threadname {get {return _ threadname;} private set {_ threadname = value ;}} // time interval int _ timeinterval; Public int timeinterval {get {return _ timeinterval;} set {_ timeinterval = value ;}// whether the current timer is enabled true: false: do not enable bool _ enabled; Public bool enabled {get {return _ enabled;} set {_ enabled = value ;}// events to be run at intervals of time public Delegate void tickeventhandler (); public event tickeventhandler tickevent; // <summary> // create a timer (constructor) /// </Summary> /// <Param name = "threadname"> thread name </param> /// <Param name = "timeinterval"> interval </Param> Public timertest (string threadname, int timeinterval = int. maxvalue) {This. threadname = threadname; this. timeinterval = timeinterval; this. enabled = false;} // <summary> // periodically execute the event // </sum Mary> Public void run () {While (true) {// if the current timer is not enabled, check whether if (! This. enabled) {thread. Sleep (100); continue;} // trigger event tickevent if (tickevent! = NULL) {tickevent () ;}// sleep for a certain period of time, waiting for the next loop thread. sleep (timeinterval % 100); For (INT temp = 0; temp <timeinterval/100; temp ++) {thread. sleep (100); If (! This. enabled) {break ;}}}}}
Iii. Call example
Output the current time every 1000 milliseconds
/// <Summary> /// Test Event /// </Summary> static void testhandler () {// todo console. writeline (datetime. now. tolongtimestring ();} static void main (string [] ARGs) {timertest TT = new timertest ("timer_test", 1000); TT. enabled = true; TT. tickevent + = testhandler; thread timer = new thread (TT. run); timer. start (); console. readline ();}
Iv. Running results
End