2012-05-09 30 views
1

我試圖抽象system.threading.timer這篇文章: http://www.derickbailey.com/CommentView,guid,783f22ad-287b-4017-904c-fdae46719a53.aspx定時器射擊錯間隔

然而,似乎定時器根據錯誤的參數

在射擊類下面我們就這條線

timer = new System.Threading.Timer(o => TimerExecute(), null, 1000, 30000); 

這應該意味着等待1秒開始之前,再火,每隔30秒

然而,代碼發射每隔一秒

我做了什麼錯

public interface ITimer 
    { 
     void Start(Action action); 
     void Stop(); 
    } 

    public class Timer : ITimer, IDisposable 
    { 
     private TimeSpan timerInterval; 
     private System.Threading.Timer timer; 
     private Action timerAction; 

     private bool IsRunning { get; set; } 

     public Timer(TimeSpan timerInterval) 
     { 
      this.timerInterval = timerInterval; 
     } 

     public void Dispose() 
     { 
      StopTimer(); 
     } 

     public void Start(Action action) 
     { 
      timerAction = action; 
      IsRunning = true; 
      StartTimer(); 
     } 

     public void Stop() 
     { 
      IsRunning = false; 
      StopTimer(); 
     } 

     private void StartTimer() 
     { 
      timer = new System.Threading.Timer(o => TimerExecute(), null, 1000, Convert.ToInt32(timerInterval.TotalMilliseconds)); 
     } 

     private void StopTimer() 
     { 
      if (timer != null) 
      { 
       timer.Change(Timeout.Infinite, Timeout.Infinite); 
       timer.Dispose(); 
       timer = null; 
      } 
     } 

     private void TimerExecute() 
     { 
      try 
      { 
       StopTimer(); 
       timerAction(); 
      } 
      finally 
      { 
       if (IsRunning) 
        StartTimer(); 
      } 
     } 
    } 
+2

您正在將timerInterval傳遞給Timer類,並稍後使用它來設置重複間隔。 timerInterval的價值是什麼? –

+0

爲了在此處粘貼它,我將代碼更改爲硬編碼值。猜猜這只是造成了混亂 – ChrisCa

回答

3

您重新啓動每次打TimerExecute時間的計時器。而且由於它重新啓動,它會在1秒後再次觸發。所以我會重寫TimerExecute。

此外,你的嘗試抓住或嘗試最後的方法,確保你實際上捕捉問題,並以某種方式處理它們,而不是忽略它。

private void TimerExecute() 
    { 
     try 
     { 
      timerAction(); 
     } 
     catch 
     { 
      //todo 
     } 
    }