Firstly, pick the right kind of timer. You want either System.Timers.Timer
or System.Threading.Timer
- don't use one associated with a UI framework (e.g. System.Windows.Forms.Timer
or DispatcherTimer
).
Timers are generally simple
- set the tick interval
- Add a handler to the
Elapsed
event (or pass it a callback on construction),
- Start the timer if necessary (different classes work differently)
and all will be well.
Samples:
// System.Threading.Timer sample
using System;
using System.Threading;
class Test
{
static void Main()
{
TimerCallback callback = PerformTimerOperation;
Timer timer = new Timer(callback);
timer.Change(TimeSpan.Zero, TimeSpan.FromSeconds(1));
// Let the timer run for 10 seconds before the main
// thread exits and the process terminates
Thread.Sleep(10000);
}
static void PerformTimerOperation(object state)
{
Console.WriteLine("Timer ticked...");
}
}
// System.Timers.Timer example
using System;
using System.Threading;
using System.Timers;
// Disambiguate the meaning of "Timer"
using Timer = System.Timers.Timer;
class Test
{
static void Main()
{
Timer timer = new Timer();
timer.Elapsed += PerformTimerOperation;
timer.Interval = TimeSpan.FromSeconds(1).TotalMilliseconds;
timer.Start();
// Let the timer run for 10 seconds before the main
// thread exits and the process terminates
Thread.Sleep(10000);
}
static void PerformTimerOperation(object sender,
ElapsedEventArgs e)
{
Console.WriteLine("Timer ticked...");
}
}
I have a bit more information on this page, although I haven't updated that for a long time.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…