我的 .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();
}
}
}
}
运行此代码后,我得到了最后一行的结果:
timerTickCounter = 1200; secondsSinceStart=1215; Stowatchseconds=1215,7573291
据您所见,计时器每秒滴答作响,但结果输出显示程序运行需要多花 15 秒的时间。
我需要更新DateTime
字段的机制,而且我不能简单地创建一个每秒滴答一次的计时器。
任何人都可以为此提出解决方案吗?