A summary of the usage of the timer class in C
- 2020-05-19 05:40:31
- OfStack
The use of the timer class in C#
The timer class in C# has three timer classes in C#
1. Defined in System.Windows.Forms
2. Defined in class System.Threading.Timer
3. Defined in class System.Timers.Timer
System. Windows. Forms Timer is applied to the WinForm, which are implemented by Windows message mechanism, similar to the Timer VB or Delphi controls, internal use API SetTimer. The main disadvantage is that the timing is imprecise and there must be a message loop that Console Application(console application) cannot use.
System.Timers.Timer and System.Threading.Timer are very similar, they are implemented through.NET Thread Pool, they are lightweight, they are timed accurately, and they have no special requirements for applications or messages. System.Timers.Timer can also be applied to WinForm, completely replacing the Timer control above. The disadvantage is that they do not support direct drag and drop and require manual coding.
Ex. :
Using System. Timers. Timer class
// instantiate the Timer class and set the interval to 10000 milliseconds;
System.Timers.Timer t = new System.Timers.Timer(10000);
// execute the event at time of arrival;
t.Elapsed += new System.Timers.ElapsedEventHandler(theout);
t. AutoReset = true; // set whether to execute once (false) or 1 straight (true);
t. Enabled = true; . / / whether System Timers. Timer. Elapsed events;
====================================
I wrote a method using class System.Timer
public class BF_CheckUpdate
{
private static object LockObject = new Object();
// Define data check Timer
private static Timer CheckUpdatetimer = new Timer();
// Check for update locks
private static int CheckUpDateLock = 0;
///
/// Set data check Timer parameter
///
internal static void GetTimerStart()
{
// Cycle interval time (10 minutes )
CheckUpdatetimer.Interval = 600000;
// allow Timer perform
CheckUpdatetimer.Enabled = true;
// Define the callback
CheckUpdatetimer.Elapsed += new ElapsedEventHandler(CheckUpdatetimer_Elapsed);
// Define multiple cycles
CheckUpdatetimer.AutoReset = true;
}
///
/// timer The event
///
///
///
private static void CheckUpdatetimer_Elapsed(object sender, ElapsedEventArgs e)
{
// Lock check for update locks
lock (LockObject)
{
if (CheckUpDateLock == 0) CheckUpDateLock = 1;
else return;
}
//More code goes here.
// Specific implementation of the function of the method
Check();
// Unlock update check lock
lock (LockObject)
{
CheckUpDateLock = 0;
}
}
}