2013-01-05 37 views
0

我在.NET應用程序中遇到了Threading.Timer問題。 爲了讓我更容易理解,我做了一個示例。System.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字段的機制,我不能簡單地創建一個定時器,每秒一次滴答。

任何人都可以爲此提出解決方案嗎?

+0

從另一邊來看它。你需要多少準確性?你有校準點嗎? –

+0

如果說得對,我需要一個確切的準確度。不,我沒有校準點。 –

回答

1

所有計時器都以〜20ms的分辨率運行。因此20分鐘15秒在預期範圍內。

如果您確實需要非常準確的1秒計時器,則需要使用一次性計時器並計算每秒的剩餘秒數。

+0

你是否善意地解釋它,我不明白。你的意思是我需要記住每個滴答的DateTime.Now並計算(Now - PrevTime)? –

+0

是的。您需要重新同步,每小時/分鐘/秒一次。 DateTime.Now是您唯一的固定參考點。 –

+0

現在我明白了。謝謝。從來沒有想過這樣簡單的操作會花費很多努力。 –