tags:

views:

35

answers:

2

Hi, 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  A: 

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
SLaks
The thing is, the part of code that is supposed to run after the timer has been set will not execute until another packet has been received. So how can I keep checking to see how long has passed? Should I put it on another thread then if a packet is found restart the timing process and repeat this?
stuartmclark
When do you want the function to run?
SLaks
The function should only run when the time that has passed is greater than the time of the interval. By this it means that the interval is over and you should be receiving another packet right now. If you don't get this packet within the interval then call the function to request a packet.
stuartmclark
Then you should make a `System.Timers.Timer` and handle its `Elapsed` event.
SLaks
Yeah this is what I originally dnoe and I stupidly never set the timer to disabled after a packet was received. So it kept timing and would always reach the time limit. Thanks again for your help.
stuartmclark
I would use a Stopwatch instead of a last DateTime in this case.
David Pfeffer
+1  A: 

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

Grant Crofton
A Stopwatch is not necessary here. (It's primarily meant for measuring performance in short intervals)
SLaks