如何立即触发事件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 ?
我找不到在 System.Timers.Timer
类。
I couldn't find any relevant property in the System.Timers.Timer
class.
推荐答案
只要打电话给 Timer_Tick
方法自己。
Just call the Timer_Tick
method yourself.
如果你不想对付蜱回调方法的参数,那么只要把代码那是在你的 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 要知道,虽然,回调会在不同的线程上运行,而不是在 Windows.Forms.Timer
它运行回调在UI线程。所以,如果你使用 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屋!