定时器运行完毕后如何停止它?
我有一个控制台应用程序,在主方法中,我有这样的代码:
Timer time = new Timer(seconds * 1000); //to milliseconds
time.Enabled = true;
time.Elapsed += new ElapsedEventHandler(time_Elapsed);
我只希望计时器运行一次,所以我的想法是我应该在 time_Elapsed 方法中停止计时器。但是,由于我的计时器存在于 Main() 中,因此我无法访问它。
I have a Console App and in the main method, I have code like this:
Timer time = new Timer(seconds * 1000); //to milliseconds
time.Enabled = true;
time.Elapsed += new ElapsedEventHandler(time_Elapsed);
I only want the timer to run once so my idea is that I should stop the timer in the time_Elapsed method. However, since my timer exists in Main(), I can't access it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以访问
timer_Elapsed
方法内部的计时器:上述方法将停止任何计时器触发的事件(如果您有多个计时器使用相同的处理程序,并且您希望每个计时器具有相同的行为) )。
您还可以在实例化计时器时设置行为:
You have access to the Timer inside of the
timer_Elapsed
method:The above method will stop whatever Timer fired the Event (in case you have multiple Timers using the same handler and you want each Timer to have the same behavior).
You could also set the behavior when you instantiate the Timer:
一个小示例应用程序:
A little example app:
我假设您使用的是 System.Timers.Timer 而不是 System.Windows.Forms.Timer?
你有两个选择。
首先,可能最好的方法是将 AutoReset 属性设置为 false。这应该完全符合你的要求。
另一种选择是在事件处理程序中调用
Stop
。I assume that you're using
System.Timers.Timer
rather thanSystem.Windows.Forms.Timer
?You have two options.
First, as probably the best, is to set the
AutoReset
property tofalse
. This should do exactly what you want.The other option is to call
Stop
in the event handler.您还可以使用 System.Threading.Timer。它的构造函数采用两个与时间相关的参数:
将周期设置为 Timeout.Infinite 以防止再次触发。
You may also use the System.Threading.Timer. Its constructor takes two time-related parameters:
Set the period to Timeout.Infinite to prevent from firing again.