首先选择正确的计时器。您需要System.Timers.Timer或System.Threading.Timer – 不要使用与UI框架相关联的一个(例如System.Windows.Forms.Timer或DispatcherTimer)。
计时器一般简单
>设置刻度间隔
>向Elapsed事件添加一个处理程序(或者在构建中传递一个回调),
>如果需要启动定时器(不同的类工作不同)
一切都会好起来的。
样品:
// 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..."); } }
我有更多的信息this page,虽然我没有更新很长一段时间。