实现“计时器”的最佳方式是什么?

可能重复:
如何将计时器添加到C#控制台应用程序

什么是实现计时器的最佳方式? 代码示例会很棒! 对于这个问题,“最好”被定义为最可靠的(最less数量的失火)和精确的。 如果我指定15秒的时间间隔,我希望每15秒调用一次目标方法,而不是每10-20秒。 另一方面,我不需要纳秒精度。 在这个例子中,该方法每14.51-15.49秒就可以接受。

使用Timer类。

https://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.110).aspx

 public static void Main() { System.Timers.Timer aTimer = new System.Timers.Timer(); aTimer.Elapsed+=new ElapsedEventHandler(OnTimedEvent); aTimer.Interval=5000; aTimer.Enabled=true; Console.WriteLine("Press \'q\' to quit the sample."); while(Console.Read()!='q'); } // Specify what you want to happen when the Elapsed event is raised. private static void OnTimedEvent(object source, ElapsedEventArgs e) { Console.WriteLine("Hello World!"); } 

Elapsed事件将每隔X毫秒(由Timer对象的Interval属性指定)提高。 它会调用你指定的Event Handler方法,在上面的例子中是OnTimedEvent

通过使用System.Windows.Forms.Timer类,你可以实现你所需要的。

 System.Windows.Forms.Timer t = new System.Windows.Forms.Timer(); t.Interval = 15000; // specify interval time as you want t.Tick += new EventHandler(timer_Tick); t.Start(); void timer_Tick(object sender, EventArgs e) { //Call method } 

通过使用stop()方法,您可以停止计时器。

 t.Stop(); 

目前还不清楚你将开发哪种types的应用程序 (桌面,networking,控制台…)

一般的答案是,如果你正在开发Windows.Forms应用程序,是使用

System.Windows.Forms.Timer类。 这样做的好处是它在UI线程上运行,所以简单的定义它,订阅它的Tick事件并且每15秒运行一次你的代码。

如果你做了其他的事情,然后窗体(从问题不清楚),你可以selectSystem.Timers.Timer ,但这一个运行在其他线程,所以如果你打算从其Elapsed事件的一些UI元素,您必须通过“调用”访问来pipe理它。

ServiceBase引用到您的类,并将下面的代码放在OnStart事件中:

Constants.TimeIntervalValue = 1 (小时)..理想情况下,您应该在configuration文件中设置此值。

StartSendingMails =要在应用程序中运行的函数名称。

  protected override void OnStart(string[] args) { // It tells in what interval the service will run each time. Int32 timeInterval = Int32.Parse(Constants.TimeIntervalValue) * 60 * 60 * 1000; base.OnStart(args); TimerCallback timerDelegate = new TimerCallback(StartSendingMails); serviceTimer = new Timer(timerDelegate, null, 0, Convert.ToInt32(timeInterval)); }