Setting up an elapsed timer event

2019-08-30 01:56发布

问题:

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



标签: c# .net timer