如何立即启动timer.Elapsed事件 [英] How to fire timer.Elapsed event immediately
问题描述
我正在使用 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 ?
I couldn't find any relevant property in the System.Timers.Timer
class.
推荐答案
只需调用 Timer_Tick
方法你自己。
如果你不想处理Tick回调方法的参数,然后将您的 Timer_Tick
中的代码放入另一种方法,并从Timer_Tick中调用,然后从 Timer.Start()
call
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屋!