Briefly describe the usage differences between System. Windows. Forms. Timer and System. Timers. Timer,
System. Windows. Forms. Timer
Form-based applications
Blocking Synchronization
Single thread
A long processing time in timer results in a large timing error.
System. Timers. Timer
Service-based
Non-blocking asynchronous
Multithreading
/// <Summary> /// windows timer /// </summary> System. windows. forms. timer _ wTimer; // <summary> // The Timer generated by the application /// </summary> System. timers. timer _ tTimer; private void Form1_Load (object sender, EventArgs e) {_ wTimer = new System. windows. forms. timer (); _ wTimer. interval = 500; // set the Interval to 500 milliseconds _ wTimer. tick + = _ wTimer_Tick; _ wTimer. start (); // Start the timer _ tTimer = new System. timers. timer (); _ tTimer. interval = 500; // set the time Interval to 500 milliseconds _ tTimer. elapsed + = _ tTimer_Elapsed; // _ tTimer. start ();} void _ tTimer_Elapsed (object sender, System. timers. elapsedEventArgs e) {Print ("_ tTimer_Elapsed" + _ count. toString (); Thread. sleep (2000); // Sleep for 2 seconds _ count ++;} void _ wTimer_Tick (object sender, EventArgs e) {Print ("_ wTimer_Tick" + _ count. toString (); Thread. sleep (2000); // Sleep for 2 seconds _ count ++;} private void Print (string msg) {if (this. invokeRequired) {this. beginInvoke (Action) delegate () {textBox1.AppendText (msg + "\ r \ n ");});} else {textBox1.AppendText (msg + "\ r \ n ");}}
When _ wTimer. Start () is started, the result is output. When _ wTimer_Tick sleeps for 2 seconds, the main thread is blocked, causing the program to be suspended for 2 seconds. In addition, events are not processed before they are processed. Therefore, the _ count result is output only once at a time,.
When _ tTimer. Start () is started, a thread is added every 500 milliseconds. As long as the asynchronous process reaches the time interval, the next thread is automatically generated, regardless of whether the previous thread is processed completely.
Therefore, the results of _ count are output multiple times.
If you want to solve the problem of system. timers only generates one thread at a specified interval or waits for processing until the last processing is completed. You can add _ tTimer before processing. stop (), start _ tTimer again. start ().