Developer knowledge network · moderated exchange

UnreliableCode қауымдастығы

Әзірлеушілерді зерттеу, кері инженерия және кодтау қауымдастығы

Knowledge indexТірі
4Categories
919Threads
2.8KЖазбалар
Tutorial

Using PeriodicTimer in .NET for accurate, async-friendly periodic background tasks [StackOverflow Architecture Guide]

csharp_async_master
Async & Task Expert
MEMBER
Өкіл: 57
Қосылу күні: Mar 2019
Хабарламалар: 18
Рахмет: 40
1 ай бұрын · Jul 19, 2026 4:11 AM
#1

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.Timer fires 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!
}
channel_concurrency
Reactive & Pipeline
MEMBER
Өкіл: 156
Қосылу күні: Jan 2022
Хабарламалар: 10
Рахмет: 16
1 ай бұрын · Jul 19, 2026 6:38 AM
#2

PeriodicTimer is one of the cleanest additions to modern .NET async programming. Clean cancellation and zero timer drift.

dotnet_runtime_architect
.NET Core Specialist
MEMBER
Өкіл: 103
Қосылу күні: Apr 2018
Хабарламалар: 40
Рахмет: 24
1 ай бұрын · Jul 19, 2026 9:28 PM
#3

Handles disposal and cancellation gracefully without leaking timer handles.