delphi 定时器的滴答声比定时器服务中断例程快 [英] delphi timer ticks faster than timer service interrupt routine

查看:28
本文介绍了delphi 定时器的滴答声比定时器服务中断例程快的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被要求为某人维护一个基于 Delphi 5 的程序,该程序使用一个计时器对象每 50 毫秒进行一次滴答,并且在每次超时时运行单线程代码块.我只是想知道,如果执行此代码块所花费的时间长于计时器滴答间隔会发生什么,这会不会很糟糕?例如,它会导致访问冲突等问题吗?Delphi默认是如何处理这种情况的?非常感谢.

Hi I have been asked to maintain a Delphi 5 based program for someone, and the program is using a timer object to tick every 50 milli-seconds and upon each time-up it runs the block of single threaded code. I am just wondering, what would happen if the time taken to execute this block of code is longer than the timer tick interval, would this be bad? For example could it cause problems like access violation? How does Delphi handle this kind of situation by default? Thanks a lot.

推荐答案

计时器的滴答声不会中断您的代码.

Ticks of the timer do not interrupt your code.

计时器滴答以窗口消息的形式传递.窗口消息只有在您检查消息队列中是否有新消息时才能到达.当您的计时器事件处理程序返回并且您的程序恢复其事件循环时,这会自动发生,但您可以通过调用 Application.ProcessMessages 显式触发它.不过,不要这样称呼;从长远来看,它很少能解决问题.

Timer ticks are delivered in the form of window messages. Window messages can only arrive when you check the message queue for new messages. That happens automatically when your timer event handler returns and your program resumes its event loop, but you can trigger it explicitly by calling Application.ProcessMessages. Don't call that, though; it seldom solves problems in the long run.

如果您不检查 timer-tick 处理程序中的消息队列,那么您的处理程序将永远不会在处理前一个滴答时再次开始运行.

If you don't check the message queue in your timer-tick handler, then your handler will never start running a second time while it's still handling a previous tick.

即使你确实检查了队列,所发生的一切都是滴答处理程序将被递归调用.毕竟,这一切都在一个线程中运行.不过,递归定时器处理可能不是您想要发生的,所以我将再次建议反对在消息处理程序中检查消息.

Even if you do check the queue, all that happens is that the tick handler will be called recursively. After all, it's all running in a single thread. Recursive timer handling probably isn't what you want to happen, though, so I'll again counsel against checking for messages in a message handler.

此外,如果您的计时器处理程序需要很长时间才能运行,则计时器消息永远不会堆积".计时器消息是假的",因为它们实际上并没有定期添加到消息队列中.相反,操作系统将在您的程序检查队列以获取更多消息时合成一个计时器消息.如果队列中没有更高优先级的消息,并且计时器间隔已过,则操作系统将返回 wm_Timer 消息.如果您检查更多消息,则队列中将没有计时器消息.特别是,队列中不会有多个定时器消息.

Furthermore, timer messages can never "pile up" if your timer handler takes a long time to run. Timer messages are "fake" in that they don't actually get added to the message queue at regular intervals. Instead, the OS will synthesize a timer message at the time your program checks the queue for more messages. If there are no higher-priority messages in the queue, and the timer interval has elapsed, then the OS will return a wm_Timer message. If you don't check for more messages, then there will be no timer message in the queue. In particular, there will not be multiple timer messages in the queue.

进一步阅读:

这篇关于delphi 定时器的滴答声比定时器服务中断例程快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆