Introduction
.Net provides lots of types of Timer classes that you, as a developer, probably have come across in your day-to-day work. Below is the list:
- System.Web.UI.Timer
- System.Windows.Forms.Timer
- System.Timers.Timer
- System.Threading.Timer
- System.Windows.Threading.DispatcherTimer
.NET 6 introduces one more timer class, called
PeriodicTimer. It doesn't rely on callbacks and instead waits asynchronously for timer
ticks. So, if you don't want to use the callbacks as it has their own flaws
PeriodicTimer is a good
alternative.
You can create the new PeriodicTimer instance by passing the one argument,
Period the time interval in milliseconds between invocations
How to use Periodic Timer
You can call the
WaitForNextTickAsync method
in an infinite for or while loop to wait asynchronously between ticks.
Example
Let's write a small console application with two methods having their own
PeridicTimer instances, one is configured to tick every minute, and another
one that ticks every second.
With every tick, increase the counter by one and print it in the console.
another one, which sets the second counter to 0 as every minute elapses.
that way we have two PeriodicTimer running parallelly without blocking each other and here is the result.
Output:
Key Notes
- This timer is intended to be used only by a single consumer at a time
- You can either use the CancellationToken or call the Dispose() method to interrupt it and cause WaitForNextTickAsync to return false
- Documentation: https://learn.microsoft.com/en-us/dotnet/api/system.threading.periodictimer?view=net-6.0
Comments