如何立即触发 timer.Elapsed 事件

编程入门 行业动态 更新时间:2024-10-22 19:40:41
本文介绍了如何立即触发 timer.Elapsed 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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:关键词]

本文发布于:2023-03-28 18:31:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/737023.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:事件   timer   Elapsed

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!