C # self-made timer on the console

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.