In C # The Timer class has 3 in C # about the Timer class
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, it is implemented through the Windows messaging mechanism, similar to the Timer control in VB or Delphi, the internal use of API SetTimer implementation. Its main disadvantage is that the timing is imprecise and that 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, lightweight, timed accurately, with no special requirements for applications or messages. System.Timers.Timer can also be applied to WinForm to completely replace the timer control above. Their disadvantage is that they do not support direct drag-and-drop and require manual coding.
Cases:
| The code is as follows |
Copy Code |
Using the System.Timers.Timer class Instantiate the Timer class, setting a time interval of 10000 milliseconds; System.Timers.Timer t = new System.Timers.Timer (10000); The time of arrival to execute the event; t.elapsed + = new System.Timers.ElapsedEventHandler (theout); T.autoreset = true;//Whether the setting is executed once (false) or always (true); t.enabled = true;//Whether the System.Timers.Timer.Elapsed event is executed; |
====================================
Write yourself a method of using the System.timer class
| The code is as follows |
Copy Code |
| public class Bf_checkupdate { private static Object lockobject = new Object ();
Define Data checking Timer private static Timer Checkupdatetimer = new timer ();
Checking for update locks private static int checkupdatelock = 0;
/// Set data Check timer parameters /// internal static void Gettimerstart () { Cycle time interval (10 minutes) Checkupdatetimer.interval = 600000; Allow Timer to execute Checkupdatetimer.enabled = true; Define Callback checkupdatetimer.elapsed + = new Elapsedeventhandler (checkupdatetimer_elapsed); Define multiple loops Checkupdatetimer.autoreset = true; }
/// Timer Event /// /// /// private static void Checkupdatetimer_elapsed (object sender, Elapsedeventargs e) { Lock Check Update lock Lock (LockObject) { if (Checkupdatelock = = 0) Checkupdatelock = 1; else return; } More code goes here. The method of realizing function concretely Check (); Unlock Update check Lock Lock (LockObject) { Checkupdatelock = 0; } } } |