DEV Community

Cover image for PeriodicTimer vs System.Threading.Timer
Maayur Dahake
Maayur Dahake

Posted on

PeriodicTimer vs System.Threading.Timer

PeriodicTimer vs System.Threading.Timer

When building background workers in .NET, the classic System.Threading.Timer has been a staple for decades. However, its callback signature TimerCallback(object? state) is inherently synchronous (void). Developers frequently resort to async-void lambdas inside the constructor, leading to unhandled exception crashes and thread pool starvation during slow iterations.

.NET 6 introduced PeriodicTimer, designed specifically for asynchronous background loops using modern async/await mechanics.

Before

var timer = new Timer(async _ => {
    await ProcessQueueAsync();
}, null, 0, 1000);
Enter fullscreen mode Exit fullscreen mode

After

using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1));

while (await timer.WaitForNextTickAsync()) {
    await ProcessQueueAsync();
}
Enter fullscreen mode Exit fullscreen mode

Why it matters

• Async Safety: WaitForNextTickAsync integrates cleanly with standard task continuations, avoiding async-void pitfalls.
• Reentrancy Control: Unlike callback timers that fire blindly on an interval, sequential loop execution prevents overlapping workloads.
• Resource Cleanup: Implements IDisposable and provides clean cancellation token propagation.

Watch out: If your background work exceeds the interval duration, PeriodicTimer queues ticks sequentially rather than overlapping, but disposing the timer mid-tick will immediately cancel the active WaitForNextTickAsync awaiter.

How do you structure your background workers in production?

Top comments (0)