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 .…