简体   繁体   English

如何避免计时器滴答中断主线程?

[英]How to avoid timer tick interrupting main thread?

I have a timer that does something when it ticks. 我有一个计时器,它在滴答时会执行某些操作。 I'm facing an issue where, while the main thread is processing something and the timer ticks, the main thread is interrupted by the action invoked by the timer tick event. 我面临的一个问题是,虽然主线程正在处理某些事情并且计时器滴答,但主线程却被计时器滴答事件所调用的动作打断了。

Is there a way to program so that the process in the main thread is completed, then only execute the action invoked by the timer tick event? 有没有一种编程方法可以使主线程中的进程完成,然后仅执行由计时器滴答事件调用的操作?

Thanks! 谢谢!

The Tick event of the WinForms Timer is raised on the UI thread, thus the event handler is executed on the UI thread. WinForms TimerTick事件在UI线程上引发,因此事件处理程序在UI线程上执行。 You could then initiate a task that was executed on a secondary thread in order to keep the UI thread free. 然后,您可以启动在辅助线程上执行的任务,以保持UI线程空闲。 Keep in mind though, any time you interact with the UI, eg get or set the Text of a TextBox , you must do it on the UI thread. 但是请记住,任何时候与UI交互,例如获取或设置TextBoxText ,都必须在UI线程上进行。

Alternatively, you can use the System.Timers.Timer class instead. 或者,可以改用System.Timers.Timer类。 By default, it's Elapsed event is raised on a secondary thread, so no extra work is required. 默认情况下,它的Elapsed事件在辅助线程上引发,因此不需要额外的工作。 If you set the SynchronizingObject property then the event will be raised on the thread that owns that object, otherwise it will be raised on a thread pool thread. 如果设置SynchronizingObject属性,则将在拥有该对象的线程上引发该事件,否则将在线程池线程上引发该事件。

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

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