Date:

Share:

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

Related Articles

There may be times when you need to process a specific task in time, such as endpoint survey To check for updates or refresh a refresh token.

If you need infinite processing, you can choose two ways: the obvious or the better.

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

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

There’s nothing wrong with that – but we can do better.

Introduction to System.Timers.Timer

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

You then set up the timer, choose which events to process, 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 builder receives an interval input (a double value representing the milliseconds for the interval), whose default value is 100.

This department implements IDisposable: if you use it as a dependency of another component it must be DisposeD, don’t forget to call Dispose on this timer.

Note: Only use this for synchronous tasks: There are other types of timers you can use for asynchronous operations, such as PeriodicTimerwhich can also be stopped by canceling a CancellationToken.

This article first appeared on Code4IT 🐧

Happy coding!

🐧

.

Source

Popular Articles