不准确的.NET计时器? [英] inaccurate .NET timer?

查看:198
本文介绍了不准确的.NET计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发一个应用程序,我需要从服务器(它不同于机器的日期)获得当前的日期。 我收到来自服务器的日期和用一个简单的拆分我创建一个新的日期时间:

I'm developing an application and I need to get the current date from a server (it differs from the machine's date). I receive the date from the server and with a simple Split I create a new DateTime:

globalVars.fec = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, int.Parse(infoHour[0]), int.Parse(infoHour[1]), int.Parse(infoHour[2]));

globalVars是一类和FEC是一个公共静态变量,这样我可以在任何地方访问它的应用程序(坏的编码,我知道...)。 现在,我需要有一个定时检查,如果该日期等于一些日期我已存储在一个列表和它是否等于我只是调用一个函数。

globalVars is a class and fec is a public static variable so that I can access it anywhere in the application (bad coding I know...). Now I need to have a timer checking if that date is equal to some dates I have stored in a List and if it is equal I just call a function.

List<DateTime> fechas = new List<DateTime>();

必须获得我所用计算机的日期服务器的日期,所以检查的日期一致,我用这个之前:

Before having to obtain the date from a server I was using computer's date, so to check if the dates matched I was using this:

private void timerDatesMatch_Tick(object sender, EventArgs e)
{
    DateTime tick = DateTime.Now;
    foreach (DateTime dt in fechas)
    {
        if (dt == tick)
        {
            //blahblah
        }
    }
}

现在我有这样DateTime.Now不能在这里使用的服务器的日期。相反,我创建了一个新的计时器间隔= 1000和蜱我加入1秒用来globalVars.fec:

Now I have the date from the server so DateTime.Now can't be used here. Instead I have created a new timer with Interval=1000 and on tick I'm adding 1 second to globalVars.fec using:

globalVars.fec = globalVars.fec.AddSeconds(1);

但时钟是不准确的和,每30分钟的时钟失去约30秒。

But the clock isn't accurate and every 30 mins the clock loses about 30 seconds.

有没有做什么,我想要做的另一种方式?我已经想过使用threading.timer代替,但我需要获得其他线程和非静态的功能。

Is there another way of doing what I'm trying to do? I've thought about using threading.timer instead but I need to have access to other threads and non-static functions.

推荐答案

存储服务器的时间与本地时间之间的区别。计算你需要的时候使用不同的服务器的时间。

Store the difference between the server's time and local time. Calculate the servers' time when you need it using that difference.

这篇关于不准确的.NET计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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