C # implementation of three timers

Source: Internet
Author: User
Tags net thread

· For the timer class in C #, there are three timer classes in C #.

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! ");

}

 

 

 

 

Experiment Analysis on the similarities and differences between the three timers in C #

 

Http://dotnet.chinaitlab.com/CSharp/737740.html

 

 

C # provides three types of Timers:

 

1. Windows-based standard Timer (System. Windows. Forms. Timer)

 

2. server-based Timer (System. Timers. Timer)

 

3. Thread Timer (System. Threading. Timer)

 

Next I will use some small experiments to analyze the similarities and differences between the three timers, especially those related to threads.

 

Example:

 

 

 

1. Windows-based standard Timer (System. Windows. Forms. Timer)

 

Note that the Windows timer is designed for a Single-threaded environment.

 

This timer exists in this product since Visual Basic 1.0 and has not been modified.

 

This Timer is the easiest way to use. You only need to drag the Timer control in the toolbox to the form, and set the attributes such as event and interval.

 

The results of the experiment fully conform to the characteristics of a single thread:

 

1. When this timer is started, the subthread ID is displayed in the subthread ID list in the lower end, and is the same as the primary thread ID.

 

Private void formsTimer_Tick (object sender, EventArgs e)

 

{

 

I ++;

 

LblSubThread. Text + = "subthread execution, Thread ID:" + System. Threading. Thread. CurrentThread. ManagedThreadId. ToString () + "\ r \ n ";

 

}

 

 

 

 

2. After you click the main thread to pause for 5 seconds, the sub-thread will pause the execution, and the sub-thread will not be paused after 5 seconds, instead, execute the subthread directly (that is, a few lines of value will be output)

 

System. Threading. Thread. Sleep (5000 );

 

3. Suspending the sub-process event for 5 seconds will result in no response for the main window for 5 seconds.

 

4. Define a static thread variable:

 

[ThreadStatic]

 

Private static int I = 0;

 

Add one in the subthread event, and click the static variable value of the thread to obtain the added I value.

 

Ii. server-based Timer (System. Timers. Timer)

 

System. Timers. Timer does not rely on the form. It is used to wake up the thread from the thread pool. It is the updated version after the traditional Timer is optimized to run in the server environment.

 

No ready-made controls are provided in the VS2005 toolbox and need to be manually coded to use this timer

 

You can use either of the following methods,

 

1. The SynchronizingObject attribute is attached to the form.

 

System. Timers. Timer timersTimer = new System. Timers. Timer ();

 

TimersTimer. Enabled = false;

 

TimersTimer. Interval = 100;

 

TimersTimer. Elapsed + = new System. Timers. ElapsedEventHandler (timersTimer_Elapsed );

 

TimersTimer. SynchronizingObject = this;

 

In this way, the experiment works almost the same as the Windows-based standard timer, but in the second experiment above, although the sub-thread execution will be suspended, however, after five seconds, all the previously queued tasks will be executed (that is, the number of rows will not be output less)

 

2. Do not use the SynchronizingObject attribute

 

This is a multi-threaded approach, that is, the starting sub-thread and the main form are not in one thread. However, there is also a problem: Because the subthread is a separate thread, it cannot access the controls in the form and can only be accessed through proxy:

 

Delegate void SetTextCallback (string text );

 

Source: (http://blog.sina.com.cn/s/blog_5aeeb8200100bhc4.html)-(turn) C # Comparison of Three timer objects in _ dash _ Sina Blog

.

 

.

 

Void timersTimer_Elapsed (object sender, System. Timers. ElapsedEventArgs e)

 

{

 

// Use proxy

 

String text = "subthread execution, Thread ID:" + System. Threading. Thread. CurrentThread. ManagedThreadId. ToString () + "\ r \ n ";

 

SetTextCallback d = new SetTextCallback (SetText );

 

This. Invoke (d, new object [] {text });

 

I ++;

 

}

 

Private void SetText (string text)

 

{

 

LblSubThread. Text + = text;

 

}

 

In this way, the following results will be obtained after the experiment again:

 

1. When this timer is started, the subthread ID is displayed in the subthread ID list in the lower end, and is different from the primary thread ID.

 

 

 

2. After you click the main thread to pause for 5 seconds, the sub-thread will continue to execute (the interface can not be seen, but it can be easily seen by outputting files in the sub-thread)

 

3. Suspending the sub-process event for 5 seconds does not cause no response to the main window.

 

4. In a subthread event, add a static variable to the thread each time, and click whether the value of the static variable in the thread is 0 (the static variable in the main window will not be changed)

 

Iii. Thread Timer (System. Threading. Timer)

 

The thread timer does not depend on the form. It is a simple and lightweight timer. It uses the callback method rather than the event and is supported by the thread pool thread.

 

Thread timers are very useful in scenarios where messages are not sent by threads.

 

The usage is as follows:

 

System. Threading. Timer threadTimer;

 

Public void ThreadMethod (Object state)

 

{

 

// Use proxy

 

String text = "subthread execution, Thread ID:" + System. Threading. Thread. CurrentThread. ManagedThreadId. ToString () + "\ r \ n ";

 

SetTextCallback d = new SetTextCallback (SetText );

 

This. Invoke (d, new object [] {text });

 

I ++;

 

}

 

Private void Form1_Load (object sender, EventArgs e)

 

{

 

ThreadTimer = new System. Threading. Timer (new System. Threading. TimerCallback (ThreadMethod), null,-1,-1 );

 

}

 

Pause code:

 

ThreadTimer. Change (-1,-1 );

 

The experiment works in the same way as the server-based Timer (System. Timers. Timer,

 

Of course, the specific usage method and principle are different. The most important thing is that this method uses the proxy method instead of the event method, and can be executed independently without relying on forms and components.

 

A table summarized by foreigners is listed below (the difference between the three methods ):

 

Feature description System. Timers. Timer System. Threading. Timer System. Windows. Forms. Timer

 

Support for adding and removing listeners after the timer is instantiated. Yes No Yes

 

Supports call backs on the user-interface thread Yes No Yes

 

Callback from threads obtained from the thread pool Yes No

 

Supports drag-and-drop in the Windows Forms Designer Yes No Yes

 

Suitable for running in a server multi-threaded environment Yes No

 

Except des support for passing arbitrary state from the timer initialization to the callback. No Yes No

 

Implements IDisposable Yes

 

Supports one-off callbacks as well as periodic repeating callbacks Yes

 

Accessible implements SS application domain boundaries Yes

 

Supports IComponent-hostable in an IContainer Yes No Yes

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.