C# 计时器在它们的间隔时间之前被触发 [英] C# timer getting fired before their interval time

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

问题描述

我们在使用 Windows 服务中的 System.Threading.Timer (.NET 2.0) 时遇到以下问题.

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 发出信号,它会在 7 秒前的 4:59:52 发出信号.

有人可以告诉我这种行为的原因是什么以及解决方法是什么?

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.

相反,如果您需要更精确的计时器 - 您必须捕获开始时的 DateTime,然后在您的计时器中,您必须通过减去 DateTime.Now 和您的原始时间来检查它是否是时间运行您的代码.

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.

以下是您需要执行的一些示例代码:

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.
}

上面的代码将每 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天全站免登陆