简体   繁体   English

启动计时器后如何防止滴答声事件

[英]How to prevent a Tick event after a Timer has already been initiated

So I have a Timer object that I'm going to call time, and time has a tick event that is called after 60 seconds are passed. 因此,我有一个要调用时间的Timer对象,并且时间有一个滴答事件,在经过60秒后将被调用。 I'm trying to use the time.Stop() method, but the time_Tick() is still called. 我正在尝试使用time.Stop()方法,但仍调用time_Tick()。 How do I prevent the Tick method from occuring? 如何防止Tick方法发生? Once the Timer has started is there no way of backing out? 计时器启动后,是否无法退出? Thanks! 谢谢! I'm new to Tick events. 我是Tick活动的新手。

Timer ticks can arrive concurrently and after the timer has been stopped (for fundamental reasons). 计时器滴答可以同时到达,也可以在计时器停止后到达(出于根本原因)。 Ticks could be queued right before you stop the timer. 滴答声可能会在您停止计时器之前排队。

If you want to reliably stop a timer set a boolean flag and inspect that flag in the tick event handler. 如果要可靠地停止计时器,请设置一个布尔标志并在tick事件处理程序中检查该标志。 If it's set ignore the tick. 如果已设置,请忽略勾号。

You need to synchronize access to that flag. 您需要同步对该标志的访问。

If you have other timer objects you may be seeing this : 如果您还有其他计时器对象,则可能会看到以下内容

Calling Stop on any Timer within a Windows Forms application can cause messages from other Timer components in the application to be processed immediately, because all Timer components operate on the main application thread. 在Windows Forms应用程序内的任何计时器上调用Stop可能导致来自应用程序中其他Timer组件的消息立即得到处理,因为所有Timer组件均在主应用程序线程上运行。 If you have two Timer components, one set to 700 milliseconds and one set to 500 milliseconds, and you call Stop on the first Timer, your application may receive an event callback for the second component first. 如果您有两个Timer组件(一个设置为700毫秒,一个设置为500毫秒),并且在第一个Timer上调用Stop,则您的应用程序可能会首先收到第二个组件的事件回调。 If this proves problematic, consider using the Timer class in the System.Threading namespace instead. 如果证明有问题,请考虑在System.Threading命名空间中使用Timer类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM