C # Timer,
Static void Main (string [] args) {# region timer TimerDemo td = new TimerDemo ("TimerDemo", 1000); td. enabled = true; td. tickEvent + = TestHandler; Thread timer = new Thread (td. run); timer. start (); # endregion Console. readLine () ;}//< summary> /// Test Event // </summary> static void TestHandler () {Console. writeLine (DateTime. now. toLongTimeString ());}
Public class TimerDemo {// 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: bool _ Enabled is not Enabled; public bool Enabled {get {return _ Enabled;} set {_ Enabled = value ;}// the publi event to be run at intervals of time C 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 TimerDemo (string ThreadName, int TimeInterval = int. maxValue) {this. threadName = ThreadName; this. timeInterval = TimeInterval; this. enabled = false;} // <summary> // periodically execute the event // </s Ummary> 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 ;}}}}}