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.
The following example shows how to use the system. Timers. Timer timer.
Using system; using system. collections. generic; using system. componentmodel; using system. data; using system. drawing; using system. LINQ; using system. text; using system. windows. forms; using system. timers; using system. runtime. interopservices; using system. threading; namespace timer001 {public partial class form1: FORM {public form1 () {initializecomponent () ;}// instantiate the Timer class system. timers. timer atimer = new system. timers. timer (); Private void button#click (Object sender, eventargs e) {This. settimerparam ();} private void test (Object source, system. timers. elapsedeventargs e) {MessageBox. show (datetime. now. tostring ();} public void settimerparam () {// execute the event atimer at the time of arrival. elapsed + = new elapsedeventhandler (TEST); atimer. interval = 1000; atimer. autoreset = true; // if this parameter is set to false once, true is always executed. // whether to execute system. timers. timer. elapsed event atimer. enabled = true ;}}}
The result is that the current system time is displayed per second, for example: