1 か月前 · Jul 19, 2026 4:11 AM
Why PeriodicTimer is superior to System.Threading.Timer and while(true) await Task.Delay() in C#:
Task.Delay()does not account for execution duration, causing timer drift over time.System.Threading.Timerfires callbacks on threadpool threads, causing overlapping executions if work takes longer than the interval.
The Modern Solution:
CSHARP
using PeriodicTimer timer = new PeriodicTimer(TimeSpan.FromSeconds(10));
while (await timer.WaitForNextTickAsync(cancellationToken))
{
await ExecuteHeartbeatAsync(); // Guarantees no overlapping ticks!
}