问题描述
我正在使用 System.Timers.Timer
类来创建一个带有 Timer.Elapsed
事件的计时器.问题是 Timer.Elapsed
事件仅在间隔时间过去后第一次被触发.
I'm using the System.Timers.Timer
class to create a timer with an Timer.Elapsed
event. The thing is the Timer.Elapsed
event is fired for the first time only after the interval time has passed.
有没有办法在启动计时器后立即引发 Timer.Elapsed
事件?
Is there a way to raise the Timer.Elapsed
event right after starting the timer ?
我在 System.Timers.Timer
类.
推荐答案
只需自己调用 Timer_Tick
方法即可.
Just call the Timer_Tick
method yourself.
如果您不想处理 Tick 回调方法的参数,那么只需将 Timer_Tick
中的代码放入另一个方法中,然后从 Timer_Tick 和紧随其后的Timer.Start()
调用
If you don't want to deal with the Tick callback method's parameters, then just put the code that was in your Timer_Tick
into another method, and call that from the Timer_Tick and from just after the Timer.Start()
call
正如@Yahia 所指出的,您还可以使用 System.Threading.Timer
计时器,您可以将其设置为初始延迟为 0.但请注意,回调将在不同的线程上运行,而不是在 UI 线程上运行的 Windows.Forms.Timer
上的回调. 因此,如果您使用 System.Threading.Timer
(没有正确调用)它会崩溃.
As pointed out by @Yahia, you could also use the System.Threading.Timer
timer, which you can set to have an initial delay to 0. Be aware though, that the callback will run on a different thread, as opposed to the callback on the Windows.Forms.Timer
which runs on the UI thread. So if you update any UI controls using the System.Threading.Timer
(without invoking correctly) it'll crash.
这篇关于如何立即触发 timer.Elapsed 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论