设置经过计时器事件
我需要测量收到最后一个数据包和新数据包到达之间的时间差。我尝试过在 C# 中使用 Timer 类,如下所示:
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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该存储
DateTime.Now
,然后与存储的值进行比较。例如:
You should store
DateTime.Now
and then compare against the stored value.For example:
您可能想查看 System.Diagnostics.Stopwatch 类而不是使用计时器
You might want to check out the System.Diagnostics.Stopwatch class instead of using a timer