Menu

1 / 2

PeriodicTimer vs System.Threading.Timer

DEV Community: dotnet·Maayur Dahake·about 5 hours ago
#rCP3YB6Z
#devtodotnet#devto#dev#timer#async
Reading 0:00
15s threshold

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

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.