.NET 6 新特性 PeriodicTimer( 二 )

实现示例如下:
public class TimedHealthCheckService : TimerScheduledService{    public TimedHealthCheckService(ILogger<TimedHealthCheckService> logger) : base(TimeSpan.FromSeconds(5), logger)    {    }    protected override Task ExecuteInternal(CancellationToken stoppingToken)    {        Logger.LogInformation("Executing...");        return Task.CompletedTask;    }}运行输出如下:

.NET 6 新特性 PeriodicTimer

文章插图
 
More
新的 PeriodicTimer 相比之前的几个 Timer 来说 , 有下面几个特点
  • 没有 callback 来绑定事件
  • 不会发生重入 , 只允许有一个消费者 , 不允许同一个 PeriodicTimer 在不同的地方同时 WaitForNextTickAsync , 不需要自己做排他锁来实现不能重入
  • 异步化 , 之前的几个 timer 的 callback 都是同步的 , 使用新的 timer 我们可以更好的使用异步方法 , 避免写 Sync over Async 之类的代码
  • Dispose() 之后 , 该实例就无法再使用 , WaitForNextTickAsync 始终返回 false
【.NET 6 新特性 PeriodicTimer】最后来做一个题目 , 把第一个示例改造一下 , 最终代码如下:
using var cts = new CancellationTokenSource();cts.CancelAfter(TimeSpan.FromSeconds(30));using var timer = new PeriodicTimer(TimeSpan.FromSeconds(3));try{    while (await timer.WaitForNextTickAsync(cts.Token))    {        await Task.Delay(5000);        Console.WriteLine($"Timed event triggered({DateTime.Now:HH:mm:ss})");    }}catch (OperationCanceledException){    Console.WriteLine("Operation cancelled");}猜一下输出结果是什么 , Timed event triggered 会输出几次
.NET 6 新特性 PeriodicTimer

文章插图
 
References
  • https://www.ilkayilknur.com/a-new-modern-timer-api-in-dotnet-6-periodictimer
  • https://docs.microsoft.com/en-us/dotnet/api/system.threading.periodictimer?view=net-6.0
  • https://github.com/dotnet/runtime/blob/v6.0.0/src/libraries/System.Private.CoreLib/src/System/Threading/PeriodicTimer.cs
  • https://github.com/dotnet/runtime/issues/31525
  • https://github.com/WeihanLi/SamplesInPractice/blob/master/net6sample/PeriodicTimerSample/Program.cs
  • https://github.com/OpenReservation/ReservationServer/blob/dev/OpenReservation.Helper/Services/CronScheduleServiceBase.cs#L91




推荐阅读