Forms. Timer, Timers. Timer, Threading. Timer, threading. timer

Source: Internet
Author: User
Tags net thread

Forms. Timer, Timers. Timer, Threading. Timer, threading. timer

. NET Framework provides three types of Timer
 

System. Windows. Forms. Timer

System. Timers. Timer

System. Threading. Timer

 

1. System. Windows. Forms. Timer

1. Based on the Windows message loop, it is triggered in the event mode and executed in the interface thread. It is a Timer that is used a lot and timed after Timer Start (based on the set Interval) call the EvnetHandler attached to the Tick event. In the EventHandler of the Timer, you can directly obtain and modify the UI elements without any problems-because the Timer is actually called on the UI thread itself.

2. It is a Form-based timer.
3. After creation, you can use Interval to set the span between Tick and use the delegate (delegate) to hook the Tick event.
4. Call the Start and Stop methods to Start and Stop
5. It is completely based on the UI thread, so some UI-related operations will be performed in this timer.
6. Some Tick may be lost due to long UI operations.

 

For example

C # code Replication
public partial class Form1 : Form 
{ public Form1() { InitializeComponent(); } int num = 0; private void Form_Timer_Tick(object sender, EventArgs e) { label1.Text = (++num).ToString(); Thread.Sleep(3000); } private void button1_Click(object sender, EventArgs e) { Form_Timer.Start(); } private void button2_Click(object sender, EventArgs e) { Form_Timer.Stop(); } } 

 

Instance resolution

 

1. The above is a very simple function, dragging a System on the Form. windows. forms. the Timer control is named Form_Timer. In the Properties window, set the Enable attribute to true and Interval to the Timer Interval. Double-click this control to see the Form_Timer_Tick method. In this method, we asked her to constantly add a number and display it on the form. The two buttons provide the timer control function.
2. Click another form to return during execution. You will find that our form has no response. This is because we use Thread. Sleep (3000); to suspend the current Thread, and the UI loses the corresponding value. This shows that we use a single Thread for execution. That is, the thread that executes the timer is the UI thread.
3. Timer is used to trigger events at user-defined event intervals. The Windows timer is designed for a Single-threaded environment, where the UI thread is used for processing. It requires the user code to have an available UI message pump, and always operate in the same thread, or mail the call to another thread.
4. A Tick event is defined inside Timer. When we double-click this control, a line of code is actually added.
This. Form_Timer.Tick + = new System. EventHandler (this. Form_Timer_Tick );

Then, Windows associates the timer with the calling thread (UI thread ). When a timer is triggered, Windows inserts a timer message into the thread message queue. The Calling thread executes a message pump to extract the message and sends it to the callback method (the Form_Timer_Tick method here ). These are all performed in a single thread, so the UI will be suspended when the callback method is executed. Therefore, it is not recommended to use this control to execute code with limited computing or limited I/O, because this will easily lead to a false UI, and Timer called by multiple threads should be used. In addition, it should be noted that the time precision of this control is not high, and the precision is limited to 55 milliseconds.

 

 

Ii. System. Timers. Timer

 

1. The Elapsed event is not a Tick event.
2. Like System. Windows. Forms. Timer, use the Start and Stop methods.
3. The AutoReset attribute determines whether the timer starts an event and stops, or enters the start/Wait loop. System. Windows. Forms. Timer does not have this attribute.
4. Set a synchronization object for the UI control to initiate an event on the UI thread of the control.

For example

C # code Replication
public partial class Form1 : Form 
{Public Form1 () {InitializeComponent () ;}int num = 0; DateTime time1 = new DateTime (); DateTime time2 = new DateTime (); // defines the Timer System. timers. timer Timers_Timer = new System. timers. timer (); private void button#click (object sender, EventArgs e) {// manually set Timer and start to run Timers_Timer.Interval = 20; Timers_Timer.Enabled = true; Timers_Timer.Elapsed + = new System. timers. elapsedEventHandler (Timers_Timer_Elapsed); time1 = DateTime. now;} void Timers_Timer_Elapsed (object sender, System. timers. elapsedEventArgs e) {label1.Text = Convert. toString (++ num); // displays the lable Thread. sleep (3000);} private void button2_Click (object sender, EventArgs e) {// stop the execution of Timers_Timer.Enabled = false; time2 = DateTime. now; MessageBox. show (Convert. toString (time2-time1 ));}}

 

 

Iii. System. Threading. Timer

C # code Replication
public partial class Form1 : Form 
{Public Form1 () {InitializeComponent () ;}int num = 0; DateTime time1 = new DateTime (); DateTime time2 = new DateTime (); System. threading. timer Thread_Time; private void button#click (object sender, EventArgs e) {// start Thread_Time = new System. threading. timer (Thread_Timer_Method, null, 0, 20); time1 = DateTime. now;} void Thread_Timer_Method (object o) {label1.Text = Convert. toString (++ num); System. threading. thread. sleep (3000);} private void button2_Click (object sender, EventArgs e) {// stop Thread_Time.Dispose (); time2 = DateTime. now; MessageBox. show (Convert. toString (time2-time1 ));}}

Instance resolution

1. The Threading. Timer method is different from the preceding method. Therefore, all parameters are set in the constructor and the start time can be set. The start and stop methods are not provided to control the timer. It is implemented in a callback method instead of an event. There is a difference between them.
2. We only need to destroy the object to stop it. When you run it, you will find that it is the same as Timers. Timer in front, it is multi-threaded, mainly because it will not be suspended, and debugging and running reports an error. But what surprised you was that our code could not stop her. It is useless to call the Dispose method. Where is the problem? Then a test was conducted and the interval was modified to 100,200,500,100, 4000. These situations. It is found that when the interval is more than ms, it is basically stopped immediately. The shorter the execution interval, the longer the execution interval. This should be caused by running multiple threads when the interval is less than the execution time. Because all threads do not stop at the same time. The shorter the interval, the more threads, the more execution times.

 

3. System. Threading. Timer is a simple lightweight Timer that uses the callback method and is provided by the thread pool thread. It is not recommended to use Windows Forms because the callback is not performed on the user interface thread.


C # differences between the three timer types

In C #, there are three timer classes.
1. defined in System. Windows. Forms
2. defined in the System. Threading. Timer class
3. defined in the System. Timers. Timer class
System. Windows. Forms. Timer is used in WinForm. It is implemented through the Windows message mechanism. Similar to the Timer control in VB or Delphi, it is implemented using the API SetTimer internally. Its main disadvantage is that the timing is not accurate and there must be a message loop, which cannot be used by the Console Application.

System. Timers. Timer and System. Threading. Timer are very similar. They are implemented through the. NET Thread Pool. They are lightweight and time-precise, and have no special requirements on applications and messages. System. Timers. Timer can also be used in WinForm to completely replace the above Timer control. Their disadvantage is that they do not support direct drag and drop and require manual encoding.

Example:
Use the System. Timers. Timer class
System. Timers. Timer t = new System. Timers. Timer (10000); // instantiate the Timer class and set the interval to 10000 milliseconds;
T. Elapsed + = new System. Timers. ElapsedEventHandler (theout); // execute the event at the time of arrival;
T. AutoReset = true; // set whether to execute once (false) or always execute (true );
T. Enabled = true; // whether to execute the System. Timers. Timer. Elapsed event;

Public void theout (object source, System. Timers. ElapsedEventArgs e)
{
MessageBox. Show ("OK! ");
}

C # What are the differences between the three timers?

System. windows. forms. timer: This is the built-in control of winform. It must be used only in winform System. threading. timer is the thread timer. It is mainly used for linking multiple threads with each other using System. timers. timer; this is the main user winform. Other classes, because timer uses this parameter in the Form class if it is required to call the Time Thread of other classes.

Related Article

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.