C# 实现“计时器”的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12535722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the best way to implement a "timer"?
提问by Robert
What is the best way to implement a timer? A code sample would be great! For this question, "best" is defined as most reliable (least number of misfires) and precise. If I specify an interval of 15 seconds, I want the target method invoked every 15 seconds, not every 10 - 20 seconds. On the other hand, I don't need nanosecond accuracy. In this example, it would be acceptable for the method to fire every 14.51 - 15.49 seconds.
实现计时器的最佳方法是什么?代码示例会很棒!对于这个问题,“最佳”被定义为最可靠(失火次数最少)和精确。如果我指定 15 秒的间隔,我希望目标方法每 15 秒调用一次,而不是每 10 - 20 秒调用一次。另一方面,我不需要纳秒精度。在此示例中,该方法每 14.51 - 15.49 秒触发一次是可以接受的。
采纳答案by Dave Zych
Use the Timerclass.
使用Timer类。
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!");
}
The Elapsedevent will be raised every X amount of milliseconds, specified by the Intervalproperty on the Timer object. It will call the Event Handlermethod you specify. In the example above, it is OnTimedEvent.
该Elapsed事件将每 X 毫秒引发一次,由IntervalTimer 对象上的属性指定。它将调用Event Handler您指定的方法。在上面的例子中,它是OnTimedEvent.
回答by Tigran
It's not clear what type of application you're going to develop(desktop, web, console...)
不清楚你要开发什么类型的应用程序(桌面、网络、控制台......)
The general answer, if you're developing Windows.Formsapplication, is use of
如果您正在开发Windows.Forms应用程序,一般的答案是使用
System.Windows.Forms.Timerclass. The benefit of this is that it runs on UIthread, so it's simple just define it, subscribe to its Tickevent and run your code on every 15 second.
System.Windows.Forms.Timer类。这样做的好处是它在UI线程上运行,所以很简单,只需定义它,订阅它的Tick事件并每 15 秒运行一次代码。
If you do something else then windows forms (it's not clear from the question), you can choose System.Timers.Timer, but thisone runs on otherthread, so if you are going to act on some UI elements from the its Elapsedevent, you have to manage it with "invoking" access.
如果你做其他事情然后 windows 窗体(从问题中不清楚),你可以选择System.Timers.Timer,但是这个在其他线程上运行,所以如果你要从它的Elapsed事件中处理一些 UI 元素,您必须通过“调用”访问来管理它。
回答by Jignesh Thakker
By using System.Windows.Forms.Timerclass you can achieve what you need.
通过使用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
}
By using stop() method you can stop timer.
通过使用 stop() 方法,您可以停止计时器。
t.Stop();
回答by A Developer
Reference ServiceBaseto your class and put the below code in the OnStartevent:
引用ServiceBase您的课程并将以下代码放入OnStart事件中:
Constants.TimeIntervalValue = 1(hour)..Ideally you should set this value in config file.
Constants.TimeIntervalValue = 1(hour)..理想情况下,您应该在配置文件中设置此值。
StartSendingMails = function name you want to run in the application.
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));
}

