Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# System.Threading.Timer时间问题_C#_.net_Time_Timer_Intervals - Fatal编程技术网

C# System.Threading.Timer时间问题

C# System.Threading.Timer时间问题,c#,.net,time,timer,intervals,C#,.net,Time,Timer,Intervals,我的.NET应用程序中的Threading.Timer有问题。 为了便于理解,我制作了一个样本 using System; using System.Diagnostics; using System.Threading; namespace TimerTestApp { class Program { private static Timer timer; private static int timerTickCounter;

我的.NET应用程序中的Threading.Timer有问题。 为了便于理解,我制作了一个样本

using System;
using System.Diagnostics;
using System.Threading;

namespace TimerTestApp
{
    class Program
    {
        private static Timer timer;
        private static int timerTickCounter;
        private static DateTime timerStartTimer;
        private static readonly Stopwatch Sw = new Stopwatch();
        private static readonly ManualResetEvent TimerFinish = new ManualResetEvent(false);

        static void Main()
        {
            Console.WriteLine("START");
            timer = new Timer(TimerCallBack, null, 0, 1000);
            TimerFinish.WaitOne();
        }

        private static void TimerCallBack(object state)
        {
            if (timerTickCounter == 0)
            {
                timerStartTimer = DateTime.Now;
                Sw.Start();
            }
            timerTickCounter++;
            Console.WriteLine("timerTickCounter = {0}", timerTickCounter);
            if (timerTickCounter >= 1200) //20.00 min
            {
                var secondsSinceStart = (int)(DateTime.Now - timerStartTimer).TotalSeconds;
                timer.Dispose();
                Sw.Stop();
                Console.WriteLine("timerTickCounter = {0}; secondsSinceStart={1}; Stowatchseconds={2}",
                                    timerTickCounter, secondsSinceStart, Sw.Elapsed.TotalSeconds);
                Console.ReadLine();
                TimerFinish.Set();
            }
        }
    }
}
运行此代码后,我有resut的最后一行:

timerTickCounter=1200;secondsSinceStart=1215;Stowatchseconds=12157573291

据你们所知,定时器每秒都在滴答作响,但最终的输出显示,程序运行的时间多了15秒

我需要更新
DateTime
字段的机制,我不能简单地创建一个每秒滴答一次的计时器


有人能提出解决方案吗?

所有定时器都以~20ms的分辨率工作。因此,20分钟15秒在预期范围内


如果你真的需要一个非常精确的1/秒计时器,那么你就需要使用一次计时器,每次都要计算剩余的秒数

从另一边接近它。您实际需要多少准确度?你有校准点吗?如果这样说是正确的,我需要精确的精度。不,我没有校准点。请你解释一下,我不明白。你的意思是我需要记住日期时间。现在在每个刻度上计算(现在-前一个时间)?是的。您需要重新同步,每小时/分钟/秒一次。DateTime。现在是你唯一固定的参考点。现在我知道了。谢谢没想到这么简单的操作会花这么多功夫。