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();
}
}
}
您正在將timerInterval傳遞給Timer類,並稍後使用它來設置重複間隔。 timerInterval的價值是什麼? –
爲了在此處粘貼它,我將代碼更改爲硬編碼值。猜猜這只是造成了混亂 – ChrisCa