We often want to execute code at some point in the future, or repeatedly at some interval. C#’s built-in Timer class and System.Timers.Timer class make both of these tasks easy. We’ll look first at timers and then at periodic timers.
The first timer will fire ~2s after we start the program, but the second should be stopped before it has a chance to fire.
In this C# version:
We use the System.Threading.Timer class, which is similar to Go’s timer.
Instead of channels, we use the timer’s callback to execute code when the timer fires.
We use Task.Delay instead of time.Sleep for non-blocking waits.
To stop a timer, we use the Change method with Timeout.Infinite as the parameters.
We use async/await for asynchronous operations, which is more idiomatic in C# than creating separate threads.
This example demonstrates basic timer usage in C#, including creating, waiting for, and stopping timers.