Timers in .NET Part 2
John Smith
Posted on January 29, 2020
I have started to cross-post to the Dev Community website as well as on my solrevdev blog.
A previous post about Timers in .NET received an interesting reply from Katie Nelson who asked about what do do with Cancellation Tokens.
TimerCallBack
The System.Threading.Timer class has been in the original .NET Framework almost from the very beginning and the TimerCallback delegate has a method signature that does not handle CancellationTokens natively.
Trial and error
So, I span up a new dotnet new worker
project which has StartAsync and StopAsync methods that take in a CancellationToken in their method signatures and seemed like a good place to start.
After some tinkering with my original class and some research on StackOverflow, I came across this post which I used as the basis as a new improved Timer.
Improvements
Firstly I was able to improve on my original TimerTest class by replacing the field level locking object combined with its’s calls to Monitor.TryEnter(_locker)
by using the Timer’s built-in Change method.
Next up I modified the original TimerCallback DoWork method so that it called my new DoWorkAsync(CancellationToken token)
method that with a CancellationToken as a parameter does check for IsCancellationRequested
before doing my long-running work.
The class is a little more complicated than the original but it does handle ctrlc gracefully.
Source
So, here is the new and improved Timer in a new dotnet core background worker class alongside all of its project files.
Success 🎉
Posted on January 29, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.