其间隔时间之前,C#计时器被解雇 [英] C# timer getting fired before their interval time

查看:95
本文介绍了其间隔时间之前,C#计时器被解雇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们得到以下的问题,同时使​​用 System.Threading.Timer (.NET 2.0)从Windows服务。

We're getting following problem while using System.Threading.Timer (.NET 2.0) from a Windows service.

  1. 大约有12种不同的定时器对象。
  2. 在每个定时器都有适当的时间和间隔时间。这是设置正确。
  3. 据观察,经过3〜4小时,计时器开始前的时间流逝的信号。例如,如果在定时器应该信号在4时59分59秒,它被示意在4时59分52秒,7秒之前。

谁能告诉我是什么原因这种行为,什么是该解决方案?

Can someone tell me what is the cause for this behavior and what is the solution for that ?

谢谢, 斯瓦特

推荐答案

大问题......这里的原因:

Great question... and here's the reason:

时序是一件棘手的事情,当涉及到计算机......你可以的永远的依赖于一个间隔是完美的。某些计算机将滴答的计时器只有每14到15毫秒,有些更频繁地比,一些不常用。

"Timing" is a tricky thing when it comes to computers... you can never rely on an "interval" to be perfect. Some computers will 'tick' the timer only every 14 to 15 milliseconds, some more frequently than that, some less frequently.

所以:

Thread.Sleep(1);

可能采取任何地方从1到30毫秒的运行。

Could take anywhere from 1 to 30 milliseconds to run.

相反,如果你需要一个更precise定时器 - 你必须拍摄的日期时间,当你开始,然后在你的计时器你必须检查减去DateTime.Now和你原来的时间,如果看到它在时间来运行你的code。

Instead, if you need a more precise timer - you have to capture the DateTime of when you begin, and then in your timers you would have to check by subtracting DateTime.Now and your original time to see if it is "time to run" your code.

下面是什么,你需要做一些样品code:

Here's some sample code of what you need to do:

DateTime startDate = DateTime.Now;

然后就可以打开定时器,时间间隔设置为1毫秒。然后,在你的方法:

Then, start your timer with the interval set to 1 millisecond. Then, in your method:

if (DateTime.Now.Subtract(startDate).TotalSeconds % 3 == 0)
{
    // This code will fire every 3 seconds.
}

这code以上将火忠实地每3秒。你可以把它运行了10年,并且仍然会闪光每隔3秒。

That code above will fire faithfully every 3 seconds. You can leave it running for 10 years, and it will still fire every 3 seconds.

这篇关于其间隔时间之前,C#计时器被解雇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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