Skip to main content

Get your hands dirty with .Net 6 Periodic Timer!

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: 

  1. System.Web.UI.Timer
  2. System.Windows.Forms.Timer
  3. System.Timers.Timer
  4. System.Threading.Timer
  5. 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

code example

How to use Periodic Timer

You can call the WaitForNextTickAsync method in an infinite for or while loop to wait asynchronously between ticks.

code example

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.

code example

another one, which sets the second counter to 0 as every minute elapses.

code example

Now let's run them in parallel

code example

that way we have two PeriodicTimer running parallelly without blocking each other and here is the result.

Output:

Timer Console result

Key Notes


Comments