. NET provides a few timer types

Source: Internet
Author: User

Analyze problems

Among the. NET built-in types, there are 3 types of timers available to programmers:

1, System.Windows.Forms.Timer type.

2, System.Threading.Timer type.

3, System.Timers.Timer type.

In general terms, these three types all implement timed functions. What programmers usually need to do is set a break time for the timer, set the processing method at the time of arrival, and then wait for the timer to be timed and trigger the processing event, and now I will introduce the three types of features.

1. System.Windows.Forms.Timer type

From the namespace of this timer can be seen,. The purpose of this type of net design is to make it easier for programmers to use timers on the Windows interface. When a System.Windows.Forms.Timer type is constructed, the current timer is associated with the current thread. When the timer arrives, a timer message is inserted into the message queue of the current thread. The current thread processes all messages in the message queue and sends them to their respective processing methods. There is a big difference between this mechanism and timing using worker threads, in fact, the System.Windows.Forms.Timer type does not involve multi-threaded operations, and timer settings and timing methods are executed on the same thread.

Attention

This means that the System.Windows.Forms.Timer is not accurate timing, in fact, when the message is blocked, the error of the timer will be quite large, because the timer message can only be processed after all the previous messages have been processed.

2, System.Threading.Timer type.

The use of this timer type is relatively complex, but it is also a relatively optimal type of timer. The timing method of the System.Threading.Timer will be determined on the worker thread execution. All objects have a thread control, and when the next tick arrives, the thread is responsible for getting a new worker thread in the threads to execute the appropriate callback method. The basic usage method is as follows:

Threadtimer timer=New timer (new TimerCallback (threadtimerhandler),null, Timeout.infinite,timeout.infinite,threadtimer.change (Interval,interval));

3, System.Timers.Timer type.

This is a relatively old type. It can also be used by worker threads to execute callback methods, like System.Threading.Timer, but it can also be dragged and dropped onto a form control in the IDE's environment, which behaves very much like the System.Windows.Forms.Timer type when it is timed and Inaccurate.

The following code example is an example of using three timers, which is a form program.

(1) First design its interface section, the interface allows the user to select any of the three kinds of timers, and to start, Hibernate, Terminate and so on, and the interface needs to add a Windows timer control. The interface layout is as shown.

  

usingSystem.Windows.Forms;usingSystem;namespacewindowsformsapplication1{ Public Partial classTimers:form {Private Const intINTERVAL = +;//1 Second        PrivateSystem.Timers.Timer Timerstimer =NewSystem.Timers.Timer (INTERVAL); PrivateSystem.Threading.Timer Threadtimer =NULL; //This delegate is used to access the controls created in the UI thread in the worker thread        Private Delegate voidoutputdelegate (DateTime time);  Publictimers () {InitializeComponent (); }        /// <summary>        ///Start Timer/// </summary>        Private voidStart_click (Objectsender, EventArgs e) {             //Make sure all timers stop first.Windowsformstimerstop ();            Timerstimerstop ();            Threadtimerstop (); if(formstimer.checked) {Windowsformstimerstart (); }            Else if(systemtimerstimer.checked) {Timerstimerstart (); }            Else{Threadtimerstart (); }        }        /// <summary>        ///To hibernate the current thread for a period of time/// </summary>        Private voidSleep_click (Objectsender, EventArgs e) {             //Sleep 5 SecondOutput.text + ="now start sleeping for 5 seconds ."; System.Threading.Thread.Sleep (5* +); }        /// <summary>        ///Stop All Timers/// </summary>        Private voidStop_click (Objectsender, EventArgs e) {             //ensure all scheduled stopsWindowsformstimerstop ();            Timerstimerstop ();        Threadtimerstop (); }        /// <summary>        ///Empty Output/// </summary>        Private voidReset_click (Objectsender, EventArgs e) {Output.text=string.        Empty; }        #regionThree timer start-up and stop/// <summary>        ///Start Windows.Forms.Timer Timer/// </summary>        Private voidWindowsformstimerstart () {Windowsformstimer.interval=INTERVAL; Windowsformstimer.tick+=Timerhandler;        Windowsformstimer.start (); }        /// <summary>        ///Stop Windows.Forms.Timer Timer/// </summary>        Private voidWindowsformstimerstop () {windowsformstimer.stop (); }        /// <summary>        ///Start Timers.timer Timer/// </summary>        Private voidTimerstimerstart () {timerstimer.elapsed+=Timerhandler; //assigns the current form control to the synchronization object property of the Timers.timer.//to ensure that its callback method can access the control of the current UI threadTimerstimer.synchronizingobject = This;        Timerstimer.start (); }        /// <summary>        ///Stop Timers.timer Timer/// </summary>        Private voidTimerstimerstop () {timerstimer.stop (); }        /// <summary>        ///Start Threading.timer Timer///the timer starts immediately after initialization is complete/// </summary>        Private voidThreadtimerstart () {Threadtimer=NewSystem.Threading.Timer (NewSystem.Threading.TimerCallback (Threadtimerhandler),NULL, System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);        Threadtimer.change (INTERVAL, INTERVAL); }        /// <summary>        ///Stop if the Threading.timer is not stopped///This stop is used to set the interval time to infinity///Threading.timer interface is slightly different from other two timer types/// </summary>        Private voidThreadtimerstop () {if(Threadtimer! =NULL) {Threadtimer.change (System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite)            ; }        }        #endregion        #regionCallback Methods and other/// <summary>        ///how to actually execute Threading.timer/// </summary>        /// <param name= "Time" ></param>        Private voidThreadtimerhandlerui (DateTime time) {Output.text+ = time. ToString () +"System.Threading.Timer is here. \ r \ n"; }        /// <summary>        ///Threading.timer callback method, you need to use the BeginInvoke method to access the controls in the UI thread/// </summary>        /// <param name= "state" >Status Parameters</param>        Private voidThreadtimerhandler (ObjectState ) {BeginInvoke (Newoutputdelegate (Threadtimerhandlerui), DateTime.Now); }        /// <summary>        ///callback Method/// </summary>        /// <param name= "Sender" >Event Sender</param>        /// <param name= "E" >event Arguments</param>        Private voidTimerhandler (Objectsender, EventArgs e) {Output.text+ = DateTime.Now.ToString () + sender. ToString () +"It's time to go \ r \ n"; }        #endregion    }    }

Compile and run the above code, select the timer you want to test, and click the Start button to have the appropriate output to monitor the timing output. The Hibernate button causes but the front UI thread sleeps for 5 seconds, which is to experiment with different timing modes for each timer. To check how several timers differ in handling callbacks, let's analyze their output separately.

1, System.Windows.Forms.Timer timing output.

  

As shown, when the main UI thread sleeps for 5 seconds, the timer is interrupted, and the second callback method is exactly 5 seconds from the third callback method. This means that there is a serious error in timing. This is because the timer and the form are in the same thread, and all the blocking at one point causes the timer to not be timed correctly.

2.system.timers.timer timed output.

  

Please note that the Timers.timer set the synchronization block object properties in the code: Synchronizedobject. This allows it to run on the UI thread while it is also affected by blocking. Analysis output (as shown), when the main thread sleeps, System.Timers.Timer's callback method cannot be executed, but unlike System.Windows.Forms.Timer, he does not omit any timer events that should be triggered, and the 4 timed callback events that should be performed during hibernation should be performed after the main thread sleeps back. So while System.Timers.Timer is not an accurate timer, it doesn't miss the beat.

3, System.Threading.Timer timing output.

  

As I have described earlier, System.Threading.Timer can be said to be a relatively optimal timer, as shown in the main UI when the thread sleeps, it does not miss any beats, and each callback is executed on schedule, because the System.Threading.Timer callback method is executed on a worker thread.

Attention

System.Timers.Timer can also be executed on worker threads, at which point the result is basically the same as System.Threading.Timer. But System.Timers.Timer still uses the older timing mechanism, the author suggests not to use System.Timers.Timer.

Answer

. NET has three timer types in the built-in type, namely:

1, System.Windows.Forms.Timer type.

2, System.Timers.Timer type.

3, System.Threading.Timer type.

System.Windows.Forms.Timer is used for form design, and runs in the form thread, which leads to the characteristics of inaccurate timing and missed beats; Each timing callback for the System.Threading.Timer type executes on a worker thread with a relatively accurate timing; System.Timers.Timer can be regarded as a wrapper of System.Threading.Timer, its type design is relatively old, I do not recommend readers to make Use the timer.

  

  

. NET provides a few timer types

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.