C # Use the timer. What should I do after the next timer arrives?
------ Solution --------------------------------------------------------
At the beginning, disable the timer. You can enable the timer after the execution is complete.
When a timer regularly executes a method, the execution time may be longer than the interval, which may cause thread concurrency problems. We recommend that you add Lock.
Private static object LockObject = new Object ();
Private static void CheckUpdatetimer_Elapsed (object sender, ElapsedEventArgs e)
{
// Lock check update lock
Lock (LockObject)
{
}
}
// From command line, compile with/r: System. dll
Using System;
Using System. Timers;
Using System. Threading;
Public class Timer2
{
// Static System. Windows. Forms. Timer aTimer = new System. Windows. Forms. Timer ();
Private static System. Timers. Timer aTimer;
Static object o = new object ();
Public static void Main ()
{
// Normally, the timer is declared at the class level,
// So that it stays in scope as long as it is needed.
// If the timer is declared in a long-running method,
// KeepAlive must be used to prevent the JIT compiler
// From allowing aggressive garbage collection to occur
// Before the method ends. (See end of method .)
// System. Timers. Timer aTimer;
// Create a timer with a ten second interval.
ATimer = new System. Timers. Timer (2000 );
ATimer. Enabled = true;
// Hook up the event handler for the Elapsed event.
ATimer. Elapsed + = new ElapsedEventHandler (OnTimedEvent );
// Only raise the event the first time Interval elapses.
ATimer. AutoReset = true;
Console. WriteLine ("Press the Enter key to exit the program .");
Console. ReadLine ();
// If the timer is declared in a long-running method, use
// KeepAlive to prevent garbage collection from occurring
// Before the method ends.
// GC. KeepAlive (aTimer );
}
// Specify what you want to happen when the Elapsed event is
// Raised.
Static object name = 0;
Private static void OnTimedEvent (object source, ElapsedEventArgs e)
{
// Lock (o)
{
ATimer. Enabled = false;
Atimers. Interval = 1000;
Lock (name)
{
Name = Convert. ToInt32 (name) + 1;
Thread. CurrentThread. Name = name. ToString ();
}
Console. WriteLine (DateTime. Now. ToString () + "-" + Thread. CurrentThread. Name );
// Thread. Sleep (1000000 );
Waste ();
ATimer. Enabled = true;
}
}
/// <Summary>
/// Simulate a long operation
/// </Summary>
Public static void Waste ()
{
For (int I = 0; I <Int32.MaxValue; I ++)
{
}
// Thread. Sleep (10000 );
Console. WriteLine (DateTime. Now. ToString () + "Done-" + Thread. CurrentThread. Name );
}
}