Setting up an elapsed timer event

与世无争的帅哥 提交于 2019-12-25 04:55:44

问题


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.


回答1:


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

For example:

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



回答2:


You might want to check out the System.Diagnostics.Stopwatch class instead of using a timer



来源:https://stackoverflow.com/questions/3882818/setting-up-an-elapsed-timer-event

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!