使用Thread实现可以突破系统最小时间间隔的Timer
使用System.Timers.Timer和System.Threading.Timer创建的计时器会受系统最小时间间隔限制,在 Windows 系统中,默认的最小时间间隔为 15.6 毫秒(数据来自GPT)。Task.Run 方法来创建线程也会受此限制,故而使用Thread来进行实现,欢迎大家优化,代码如下:
public delegate void MyCallback();
class MyTimer
{
public int Interval { get; set; } = 1000;
private bool running = false;
public event MyCallback Elapsed;
private CancellationTokenSource cts;
private Thread thread;
public MyTimer()
{
cts = new CancellationTokenSource();
thread = new Thread(ExecuteTimer);
thread.Start();
}
private void ExecuteTimer()
{
Stopwatch sw = Stopwatch.StartNew();
while (!cts.Token.IsCancellationRequested)
{
if (running && sw.ElapsedMilliseconds > Interval)
{
sw.Restart();
Elapsed?.Invoke();
}
Thread.Sleep(1);
}
}
public void Start()
{
running = true;
}
public void Stop()
{
running = false;
}
public void Close()
{
cts.Cancel();
Elapsed = null;
thread.Join(); // 等待线程结束
}
}
设置频率为120次每秒,实际为100秒左右进行波动