设置经过的计时器事件 [英] Setting up an elapsed timer event

查看:33
本文介绍了设置经过的计时器事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要测量收到最后一个数据包和新数据包到达之间的时间差.我曾尝试在 C# 中使用 Timer 类:

I need to measure the time difference between when the last packet was received and the new one has arrived. I have tried using the Timer class in C# as such:

while (listening)
            {
                if (hB != null)
                {
                    interval = hB.GetHBInterval();
                    aTimer = new System.Timers.Timer(interval+5);
                    Console.WriteLine("Interval is: {0}", interval);    
                    byte[] bytes = listener.Receive(ref groupEP);
                    DecodeUDPMessage(Encoding.UTF8.GetString(bytes, 0, bytes.Length));
                }
                else
                {
                    byte[] bytes = listener.Receive(ref groupEP);
                    DecodeUDPMessage(Encoding.UTF8.GetString(bytes, 0, bytes.Length));
                }
            }

我最初拥有它是为了如果计时器在间隔的时间长度后过去,则会调用一个事件.但是意识到定时器会等待间隔的长度然后调用事件.我需要弄清楚的是,我能否计算出最后一个数据包何时到达和新数据包何时到达的区别.如果可以,那么我需要根据间隔值对其进行评估,如果它更大,则调用另一个可以做一些工作的方法.

I originally had it so that an event would be called if the timer elapsed after the length of time of the interval. But realised that the timer will wait for the length of the interval and then call the event. What I need to figure out is, can I work out the difference of when a packet came last and when the new one has arrived. If I can then I need to evaluate it against the interval value and if it is greater then call another method that will do some work.

我的大脑在试图解决这个问题时已经死了,所以任何帮助将不胜感激.

My brain has died trying to figure this out so any help would be greatly appreciated.

推荐答案

您应该存储 DateTime.Now 然后与存储的值进行比较.

You should store DateTime.Now and then compare against the stored value.

例如:

var lastTime = DateTime.Now;
//Do things...
if ((DateTime.Now - lastTime).TotalSeconds > 5)
    //Do other things

这篇关于设置经过的计时器事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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