我正在尝试根据这篇文章抽象 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();
}
}
}