System.Threading.Timer时间问题

时间:2013-01-05 17:31:52

标签: 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;
        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=1215,7573291

至于你可以看到每秒计时器滴答,但结果输出表明程序运行需要15秒的时间。

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

有人可以为此提出解决方案吗?

1 个答案:

答案 0 :(得分:1)

所有计时器的分辨率约为20ms。所以20分钟内15秒就在预期范围内。

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