From the course: Advanced .NET: Commands, C# Enhancements, Web Apps, and Libraries

Unlock this course with a free trial

Join today to access over 25,500 courses taught by industry experts.

Threading: PeriodicTimer, the solution

Threading: PeriodicTimer, the solution

- Periodic timer was created to help an async in multiple thread situations. The first difference from all the other timers is that it does not use a callback method. Instead, we await the timer tick in a while loop. We wait asynchronously for those timer ticks and that avoids overlap problems. So there's no need for us to use auto reset event or any of the other thread synchronization primitives. However, there are some benefits using some of these thread synchronization tools, and that they support an easy way to cancel operation. So periodic timer also accepts a cancellation token so we can easily cancel the operation when needed. Let's see how we work with one of these. Here, I am creating an instance of periodic timer. I'm setting it to one second. Then I have a while loop set up here. So this loop is going to run and it's going to await until it gets a buoy back from this method, wait for next tick async. So it waits…

Contents