如何使用线程计时器 [英] How to use thread timer

查看:92
本文介绍了如何使用线程计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



想知道线程计时器对象是否继续触发,即使正在执行的任务也已完成.

示例:

Hi,

Wanted to know if thread timer object continues to fire even if the task being performed it''s done.

Example:

System.Threading.Timer t = new System.Threading.Timer(MyMethod,null,0,1000);

void MyMethod(object o)
{
  // task that completes at varying times but NEVER less than the timer's interval
}

推荐答案

是的.计时器会触发TICK事件,然后立即重新启动.它不等待任务完成,而只是引发一个事件.

如果要使其停止,请使用停止例程.
Yup. The timer fires a TICK event, then restarts immediately. It does not wait for the task to complete, it just fires an event.

If you want it to stop, then use the stop routine.


如果仅在当前任务结束后才运行下一个任务,请尝试设置全局标志并在计时器内可以根据标志的状态执行新任务.
In case you to run your next task only after finishing the current task is over, try to set a global flag and within timer do new the task based on the status of flag.


一个简单的事实,即即使正在处理滴答处理程序时,计时器仍会触发,这使得使用计时器的代码易受攻击.最好尽可能避免使用计时器来使用线程.

—SA
The simple fact that a timer keeps firing even when the tick handler is being processed makes the code using timers vulnerable. It''s much better to use threads whenever possible avoiding timers.

—SA


这篇关于如何使用线程计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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