本文最后更新于 210 天前,其中的信息可能已经有所发展或是发生改变。
using System;
using System.Diagnostics;
using System.Threading;
public class MiniTimer
{
private bool enabled;
private Thread thread;
private readonly AutoResetEvent are = new(false);
private readonly Stopwatch stopwatch = new();
public event EventHandler Elapsed;
public bool Enabled
{
get => enabled;
set
{
enabled = value;
if (enabled)
StartTimer();
else
StopTimer();
}
}
public int Interval { get; set; }
public bool IsRunning => thread != null && thread.IsAlive;
public void Start() => Enabled = true;
public void Stop() => Enabled = false;
public void Wait() => thread?.Join();
public void StopAndWait()
{
Stop();
Wait();
}
private void StartTimer()
{
if (!IsRunning)
{
thread = new Thread(TimerThread);
thread.Start();
}
}
private void StopTimer()
{
if (IsRunning)
{
are.Set();
}
}
private void TimerThread()
{
while (enabled)
{
stopwatch.Restart();
Elapsed?.Invoke(this, EventArgs.Empty);
are.WaitOne(Math.Max(Interval - (int)stopwatch.ElapsedMilliseconds, 0));
}
}
}