This article is a mirror article of machine translation, please click here to jump to the original article.

View: 3427|Reply: 2

[Source] A new timer in .NET 6, PeriodicTimer, is used

[Copy link]
Posted on 8/2/2023 7:12:40 PM | | |
Requirements: Use ASP.NET Core 6 to create a new background service to poll regularly to obtain data, and use itSystem.Timers.TimerTimer polling, adding additional Monitor code to prevent repeated execution at the same time, although it meets my business needs, is not elegant enough, and using the new PeriodicTimer timer in .NET 6 can better meet my business needs.

As a developer, you may have used timers in .NET before. There are many types of timers in .NET today, each serving a different purpose. As follows:

  • System.Threading.Timer
  • System.Timers.Timer
  • System.Windows.Forms.Timer
  • System.Web.UI.Timer
  • System.Windows.Threading.DispatcherTimer


A new Timer was introduced in .NET 6 - System.Threading.PeriodicTimer, and the biggest difference compared to the previous Timers is that the event handling of the new PeriodicTimer can be used in a more convenient asynchronous way, eliminating the mechanism of using callbacks and reducing the complexity of use.

.NET 6 introduced a new timer type called PeriodicTimer. The main purpose behind PeriodicTimer is to avoid using callbacks.Avoiding callbacks saves us from dealing with memory leaks that can occur in long-term operations, and we can write async code instead of sync over async to use that method in callbacks. You may be dealing with the current timer typeAnother problem is the overlapping callbacks。 If you don't write code for callback overlap scenarios, you may see unexpected behavior in your application.

createPeriodicTimerThe instance is very simple, the only parameter you need to provide is the period value, the code is as follows:

Asynchronous Timing Background Task Code:

(End)





Previous:Base64 decoding errors exist in all versions of .NET
Next:.NET/C# generic T covariant out and inverter in interface
 Landlord| Posted on 8/2/2023 8:22:23 PM |
 Landlord| Posted on 11/12/2023 9:42:28 AM |
The service stops, and the CancellationToken notifies the cancellation of the task, resulting in the throwing:OperationCanceledExceptionabnormal
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com