Code4IT

The place for .NET enthusiasts, Azure lovers, and backend developers

C# Tip: Raise synchronous events using Timer (and not a While loop)

2022-11-29 2 min read CSharp Tips
Just a second! 🫷
If you are here, it means that you are a software developer. So, you know that storage, networking, and domain management have a cost .

If you want to support this blog, please ensure that you have disabled the adblocker for this site. I configured Google AdSense to show as few ADS as possible - I don't want to bother you with lots of ads, but I still need to add some to pay for the resources for my site.

Thank you for your understanding.
- Davide

There may be times when you need to process a specific task on a timely basis, such as polling an endpoint to look for updates or refreshing a Refresh Token.

If you need infinite processing, you can pick two roads: the obvious one or the better one.

For instance, you can use an infinite loop and put a Sleep command to delay the execution of the next task:

while(true)
{
    Thread.Sleep(2000);
    Console.WriteLine("Hello, Davide!");
}

There’s nothing wrong with it - but we can do better.

Introducing System.Timers.Timer

The System.Timers namespace exposes a cool object that you can use to achieve that result: Timer.

You then define the timer, choose which event(s) must be processed, and then run it:

void Main()
{
    System.Timers.Timer timer = new System.Timers.Timer(2000);
    timer.Elapsed += AlertMe;
    timer.Elapsed += AlertMe2;

    timer.Start();
}

void AlertMe(object sender, ElapsedEventArgs e)
{
    Console.WriteLine("Ciao Davide!");
}

void AlertMe2(object sender, ElapsedEventArgs e)
{
    Console.WriteLine("Hello Davide!");
}

The constructor accepts in input an interval (a double value that represents the milliseconds for the interval), whose default value is 100.

This class implements IDisposable: if you’re using it as a dependency of another component that must be Disposed, don’t forget to call Dispose on that Timer.

Note: use this only for synchronous tasks: there are other kinds of Timers that you can use for asynchronous operations, such as PeriodicTimer, which also can be stopped by canceling a CancellationToken.

This article first appeared on Code4IT 🐧

Happy coding!

🐧

About the author

Davide Bellone is a Principal Backend Developer with more than 10 years of professional experience with Microsoft platforms and frameworks.

He loves learning new things and sharing these learnings with others: that’s why he writes on this blog and is involved as speaker at tech conferences.

He's a Microsoft MVP πŸ†, conference speaker (here's his Sessionize Profile) and content creator on LinkedIn.