Implementation of three kinds of timers in C #

Source: Internet
Author: User
Tags net thread

• about the Timer class in C # there are 3

1. Definition 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 applied to WinForm, which is implemented through the Windows messaging mechanism, similar to the Timer control in VB or Delphi, implemented internally using the API SetTimer. The main drawback is that the timing is imprecise and there must be a message loop that the console application (console application) cannot use.

System.Timers.Timer and System.Threading.Timer are very similar, they are implemented through the. NET Thread pool, light-weight, accurate timing, no special requirements for applications, messages. System.Timers.Timer can also be applied to WinForm, completely replacing the timer control above. Their disadvantage is that they do not support direct drag-and-drop and require manual coding.

Cases:

Using the System.Timers.Timer class

System.Timers.Timer t = new System.Timers.Timer (10000);//Instantiate Timer class, set interval time is 10000 milliseconds;

t.elapsed + = new System.Timers.ElapsedEventHandler (theout);//The event is executed at time of arrival;

T.autoreset = true;//Whether the setting is executed once (false) or always executed (true);

t.enabled = true;//Whether the System.Timers.Timer.Elapsed event is performed;

public void Theout (object source, System.Timers.ElapsedEventArgs e)

{

MessageBox.Show ("ok!");

}

Experimental analysis of the similarities and differences of three timers in C #

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

There are three types of timers available in C #:

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

2. Server-Based Timers (System.Timers.Timer)

3. Thread Timer (System.Threading.Timer)

I'll go through some small experiments to specifically analyze three kinds of timers using the similarities and differences, especially the thread-related parts.

Examples of experiments:

One, Windows-based standard timer (System.Windows.Forms.Timer)

First, note that the Windows timer is designed for single-threaded environments

This timer is present in the product from the Visual Basic version 1.0 and is basically unchanged

This timer is the simplest one, just drag the Timer control from the Toolbox onto the form, then set the event and interval time properties.

The results of the experiment are also completely in line with the characteristics of single thread:

1. When this timer is started, the child thread ID is displayed in the sub-thread ID list below, and is the same as the main thread ID

private void Formstimer_tick (object sender, EventArgs e)

{

i++;

Lblsubthread.text + = "Sub-thread execution, thread ID:" + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString () + "\ r \ n";

}

2. When the main thread is paused for 5 seconds, the child thread pauses execution and, after 5 seconds, does not execute the previously paused child thread, but executes the subsequent child thread (that is, it will output a few rows less)

System.Threading.Thread.Sleep (5000);

3. Pausing for 5 seconds in the event of a child process causes the main window to respond with no response for 5 seconds

4. Define a static variable for a thread:

[ThreadStatic]

private static int i = 0;

Add one at a time in a child-thread event, and then click on the value of the thread's static variable to get the added I value

Second, server-based timers (System.Timers.Timer)

System.Timers.Timer does not rely on forms, is a wake-up thread from a thread pool, is an updated version of a traditional timer optimized for running on a server environment

No ready-made controls are available in VS2005 's toolbox and need to be manually coded to use this timer

There are two ways of using it,

1. Attach to form by SynchronizingObject attribute

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 experimental effect is almost the same as the standard Windows-based timer, but in the second experiment above, although also pauses the execution of the child threads, but after 5 seconds to the queue before the task is executed (that is, not less output a few rows of values)

2. Do not use the SynchronizingObject property

This is a multi-threaded approach, where the child threads that are started and the main form are not on a thread. However, there is also a problem: because the child thread is a separate thread, you cannot access the controls in the form and can only be accessed by proxy:

delegate void Settextcallback (string text);

Source: (http://blog.sina.com.cn/s/blog_5aeeb8200100bhc4.html)-(EXT) Comparison of three timer objects in C # _dash_ Sina Blog

void Timerstimer_elapsed (object sender, System.Timers.ElapsedEventArgs e)

{

Using proxies

string text = "Child thread 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;

}

So we can experiment again and get the following results:

1. When this timer is started, the child thread ID is displayed in the sub-thread ID list below, and is not the same as the main thread ID

2. When you click on the main thread to pause for 5 seconds, the sub-thread will continue to execute downward (the interface may not be visible, but it can be easily seen by the way the child threads output the file)

3. Pausing for 5 seconds in the event of a child process does not cause the main window to be unresponsive

4. Add one to the thread static variable at a time in the child thread event, then click on the value of the thread static variable worth or 0 (does not change the thread static variable in the main window)

Three, Thread timers (System.Threading.Timer)

The thread timer is also not dependent on the form, and is a simple, lightweight timer that uses callback methods instead of using events and is supported by thread pool threads.

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

Here's how to use it:

System.Threading.Timer Threadtimer;

public void Threadmethod (Object state)

{

Using proxies

string text = "Child thread 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 effect of the experiment and the second way of server-based timers (System.Timers.Timer) are the same,

Of course, the use of specific methods and principles are not the same, the main thing is that this way is the way to use the proxy rather than the way the event, and can not rely on forms and components to execute independently

Below is a list of the foreigners summary (three different ways):

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

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

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

Calls back from threads obtained from the thread pool Yes Yes No

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

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

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

Implements IDisposable Yes Yes

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

Accessible across application domain boundaries Yes Yes Yes

Supports icomponent–hostable in an icontainer Yes No Yes

Implementation of three kinds of timers in C #

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.