How to analyze PeriodTimer in .net 6
This article mainly analyzes how to carry out PeriodTimer analysis in. Net 6 related knowledge points, detailed and easy to understand, reasonable operation details, with certain reference value. If you are interested, you may wish to follow Xiao Bian to have a look. Let's follow Xiao Bian to learn more about "how to perform PeriodTimer analysis in. Net 6".
PeroidTimer, an asynchronous timer added to. net 6, has a simpler model than the callback of a regular Timer.
var second = TimeSpan.FromSeconds(3); using var timer = new PeriodicTimer(second);while (await timer.WaitForNextTickAsync()){ Console.WriteLine($"Tick {DateTime.Now}");}
MSDN is a bit vague about the processing strategy of WaitForNextTickAsync. I take the Timer with a period of 3s in the previous code as an example.
A simple test:
1. Execution time less than Timer period:
Adjust the execution time of each task to 2s and see the output:
Tick 2022/1/7 11:30:58
Tick 2022/1/7 11:31:01
Tick 2022/1/7 11:31:04
2. Execution cycle greater than Timer cycle:
Adjust the execution time of each task to 5s and see the output:
Tick 2022/1/7 11:33:08
Tick 2022/1/7 11:33:13
Tick 2022/1/7 11:33:18
Tick 2022/1/7 11:33:23
From these two examples, we can conclude:
When the task execution time is less than the cycle, the next trigger time is the last trigger time + cycle.
When the task execution time is longer than the period, it will be triggered immediately next time.
This article mainly analyzes how to carry out PeriodTimer analysis in. Net 6 related knowledge points, detailed and easy to understand, reasonable operation details, with certain reference value. If you are interested, you may wish to follow Xiao Bian to have a look. Let's follow Xiao Bian to learn more about "how to perform PeriodTimer analysis in. Net 6".