C# Reference ยท Async and Concurrency
Timers: PeriodicTimer and System.Threading.Timer
Reference for timers in C#: PeriodicTimer for async loops, System.Threading.Timer callbacks, System.Timers.Timer, reentrancy, disposal and cancellation.
.NET has several timers. For modern code, two matter. PeriodicTimer (since .NET 6) is made for async loops: you await timer.WaitForNextTickAsync() in a while loop and run your work between ticks. System.Threading.Timer calls a callback on a thread-pool thread at an interval; it is simple but its callbacks can overlap and exceptions can crash the process.
System.Timers.Timer wraps the same idea with an Elapsed event, and UI frameworks have their own timers (not available here). Never use a timer for precision: ticks can be late, and the exact interval is not guaranteed.
using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(100)); while (await timer.WaitForNextTickAsync()) { Console.WriteLine("tick"); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public sealed class PeriodicTimer : IDisposable { public PeriodicTimer(TimeSpan period); public TimeSpan Period { get; set; } public ValueTask<bool> WaitForNextTickAsync(CancellationToken cancellationToken = default); public void Dispose(); } public sealed class Timer : MarshalByRefObject, IDisposable, IAsyncDisposable { public Timer(TimerCallback callback); public Timer(TimerCallback callback, object? state, int dueTime, int period); public Timer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period); public bool Change(int dueTime, int period); public void Dispose(); }
| Name | Description |
|---|---|
period |
Time between ticks. Must be greater than zero (and at most about 49 days) for PeriodicTimer. Timeout.Infinite disables repeats in Threading.Timer. |
dueTime |
Delay before the first callback; 0 starts immediately; Timeout.Infinite creates the timer stopped. |
state |
Object passed to the callback. |
cancellationToken |
Cancels the wait with OperationCanceledException. |
Returns: WaitForNextTickAsync returns true for a tick and false after Dispose. Change returns true on success.
Errors: ArgumentOutOfRangeException for a non-positive PeriodicTimer period. An unhandled exception in a Threading.Timer callback terminates the process.
Usage notes
PeriodicTimersupports one waiter at a time. CallingWaitForNextTickAsynctwice concurrently throwsInvalidOperationException.- Ticks do not queue up. If your work takes longer than the period,
PeriodicTimerdelivers at most one pending tick, so the loop runs back to back instead of building a backlog. The loop never overlaps itself. Threading.Timercallbacks can overlap when they take longer than the period, and they run on pool threads. Guard shared state, or use a one-shot timer you re-arm at the end of each callback.- Keep a reference. A
Threading.Timerthat is garbage-collected stops firing. Store it in a field, or dispose it explicitly when done. Disposing does not wait for a running callback; useDisposeAsyncor a latch if you need that. - Do not
async voidthe callback. Exceptions would crash the process. Wrap the body intry/catch. - Accuracy. Resolution is coarse (a millisecond or more, depending on the OS), and busy thread pools delay callbacks. Do not compute elapsed time by counting ticks; read a
Stopwatch. - Hosted services commonly use
PeriodicTimerinsideBackgroundService.ExecuteAsync.