SoFunction
Updated on 2025-03-10

.NET 6 new features trial Timer class PeriodicTimer

Preface:

In .NET, there are already 5 Timer classes:




Regardless of the reason for this design in the past, now .NET 6 has added a new one for usTimer,​​PeriodicTimer​​。

Why is this?

1. Demo

Unlike other Timers that need to create event callbacks:

Timer timer = new Timer(delegate
{
    (3000);
    ($"Timer Thread: {}");
    ($"{} Timer tick");
},null,0,1000
);

PeriodicTimer is used as follows:

//The interval time is 1 secondusing (var timer = new PeriodicTimer((1)))
{
    //Execute the method after the specified cycle has been reached    while (await ())
    {
        await (3000);
 
        ($"Timer Thread: {}");
        ($"{} PeriodicTimer tick");
    }
}

FromawaitThe keywords can be seen,PeriodicTimerUsed for asynchronous execution; and only one thread can execute at a time.

In addition, you can control the stopping PeriodicTimer timing. The sample code is as follows:

//Create CancellationTokenSource, specifying that it will be cancelled after 3 secondsvar cts = new CancellationTokenSource((3));

using (var timer = new PeriodicTimer((1)))
{
    while (await ())
    {
        ($"{} PeriodicTimer tick");
    }
}

It should be noted that this raises an OperationCancelled exception, you need to catch the exception and then process it as needed:

Of course, you can also cancel it by proactivelyCancellationTokenSource, come to stopPeriodicTimerTime,

The sample code is as follows:

var cts = new CancellationTokenSource();

using (var timer = new PeriodicTimer((1)))
{
    int count = 0;
    while (await ())
    {
        if (++count == 3)
        {
            //Cancel after 3 executions            ();
        }
        ($"{} PeriodicTimer tick");
    }
}

This time it was replaced with the TaskCancelled exception:

If, you don't want to throw an exception, you can usemethod to stop timing,

The sample code is as follows:

using (var timer = new PeriodicTimer((1)))
{
    int count = 0;
    while (await ())
    {
        if (++count == 3)
        {
            //Cancel after 3 executions            ();
        }
        ($"{} PeriodicTimer tick");
    }
}

in conclusion:

Through the above code, we can understand that the reasons for designing PeriodicTimer can be summarized as:

  • For asynchronous context
  • Used by only one consumer at a time

This is the article about the trial of PeriodicTimer of the .NET 6 new features. This is all about this article. For more related PeriodicTimer content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!