This article is a mirror article of machine translation, please click here to jump to the original article.

View: 18870|Reply: 1

[Source] C# implementation of three timers

[Copy link]
Posted on 10/12/2017 1:12:51 PM | | |
About the timer class in C# There are three timer classes in C#

1. Define 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, it is implemented through the Windows message mechanism, similar to the Timer control in VB or Delphi, and is implemented internally using the API SetTimer. Its main drawback is that the timing is not precise and there must be a message loop, which is not available to the Console Application.



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



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 10,000 milliseconds.

t.Elapsed += new System.Timers.ElapsedEventHandler(theout); Execute events when the time is reached;

t.AutoReset = true; Set whether to execute once (false) or all the time (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!");

}



Experimental analysis of the similarities and differences between the use 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 timer (System.Timers.Timer)


3. Threading Timer (System.Threading.Timer)

Let's go through some small experiments to analyze the similarities and differences between the three timers, especially the thread-related part.

Screenshot of experimental example:



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



The first thing to note is that Windows Timer is designed for single-threaded environments



This timer has been present in the product since Visual Basic version 1.0 and has remained largely unchanged



This timer is the easiest to use, just drag the Timer control from the toolbox to the form, and set the properties such as events and intervals



The experimental results are also fully consistent with the characteristics of single threading:



1. When this timer is started, the child thread ID will be displayed in the child thread ID list below, and it is the same as the main 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. When the main thread is paused for 5 seconds, the child thread will pause the execution, and when the previously suspended child thread will not be executed after 5 seconds, the subsequent child thread will be directly executed (that is, it will output a few lines of values).



System.Threading.Thread.Sleep(5000);



3. Pausing the events of a child process for 5 seconds will cause the main window to become unresponsive for 5 seconds



4. Define a thread static variable:



[ThreadStatic]



private static int i = 0;



Add one to each subthread event, and then click on the thread static variable value to get the increased i value



2. Server-based timer (System.Timers.Timer)



System.Timers.Timer does not depend on forms, wakes threads from the thread pool, and is an updated version of the traditional timer optimized to run on a server environment



There are no out-of-the-box controls provided in the VS2005 toolbox and need to be manually coded to use this timer



There are two ways to use it,



1. Attach to the form through the SynchronizingObject property



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 a standard Windows-based timer, except that in the second experiment above, although the execution of the subthread will also be paused, but after 5 seconds all previously queued tasks will be executed (i.e. a few lines of value will not be missing).



2. Do not use the SynchronizingObject property



This method is multi-threaded, that is, the starting child thread and the main form are not on the same thread. However, there is also a problem: since the subthread is a separate thread, the controls in the form cannot be accessed, but can only be accessed through a proxy:



delegate void SetTextCallback(string text);



Source: (http://blog.sina.com.cn/s/blog_5aeeb8200100bhc4.html) - (Turn) Comparison of three timer objects in C#_dash_Sina blog









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



{



//使用代理



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;



}



In this way, we will get the following results from the experiment again:



1. When this timer is started, the child thread ID will be displayed in the child thread ID list below, and it is different from the main thread ID







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



3. Pausing the events of a child process for 5 seconds will not cause the main window to become unresponsive



4. Add one to the thread static variable each time in the sub-thread event, and then click whether the thread static variable is worth 0 or 0 (it will not change the thread static variable in the main window).



3. Threading Timer (System.Threading.Timer)



Thread timers also don't rely on forms, are simple, lightweight timers that use callback methods instead of using events, and are powered by thread pool threads.



Thread timers are 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)



{



//使用代理



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 is the same as the second way of the server-based timer (System.Timers.Timer),



Of course, the specific usage methods and principles are different, the most important thing is that this method uses the agent method instead of the event method, and can be executed separately without relying on forms and components



The following is a table summarized by foreigners (the difference between the three methods):



Feature descrip{filter}tion 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



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 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




Previous:c# Lamda expression set degrouping to take the minimum value
Next:Linq: Never use Count() > 0 to determine that the set is non-empty
Posted on 11/8/2017 2:02:44 PM |
It's true. It's really good, but why didn't you reply to the post?
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com