定时器不按间隔触发 [英] Timer not fireing on interval

查看:31
本文介绍了定时器不按间隔触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,分钟计时器事件没有在应该触发的时候触发,我将它设置为 500 毫秒的间隔,但是正如我在日志中看到的那样,这没有按预期工作.我希望代码在等待 0.5 秒时执行,然后再次开始执行!

I have a problem that min timer event is not fired when it should be, I set it to an interval of 500ms, but as I can see in my logg, this doesn't work as intended. I want the code to excecute when wait 0.5 seconds then start executing again!

    public void initilize_Rfid()
    {
        _timerComm = new System.Timers.Timer(500);
        _timerComm.Elapsed += CommTimerEvent;
        _timerComm.Enabled = true;
    }

    private void CommTimerEvent(object source, ElapsedEventArgs e)
    {
        try
        {
            _timerComm.Enabled = false;
            Logg("Inside CommTimerEvent " + _name);

            //TALKING TO A SERIALPORT AND DETERMENATING IF TO CONTINUE WITH THE TIMER

            if ((_continueTimer)
            {
                _timerComm.Enabled = true;
               Logg("Re-activating timer " + _name);
            }
        }
        catch (Exception ex) { Logg(ex.ToString()); }
    }

我可以看到文本Inisde ComTimerEvent TEST1",然后大约 0.8 秒后我得到重新激活计时器 TEST1".这一切都很好.但在此之后,我最多会延迟 3 秒,直到计时器再次触发……我可以以某种方式防止这种情况发生吗?

I can see the text "Inisde ComTimerEvent TEST1", and then about 0.8 seconds later I get my "Re-activating timer TEST1". That is all just fine. But after this I get a up to 3 seconds delay until the timer fires again... Can I prevent this in some way?

推荐答案

您可以改为使用 DispatcherTimer.以下代码将帮助您每 5 秒触发一次方法.

Instead you can Use DispatcherTimer. The following code will help you to fire a method for every 5 seconds.

DispatcherTimer LabelTimer = new DispatcherTimer();
                        LabelTimer.Interval = TimeSpan.FromSeconds(5);
                        LabelTimer.Tick += new EventHandler(TaskTimer_Tick_THROW);

这篇关于定时器不按间隔触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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