Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Timers.Timer/Threading.Timer vs Thread with WhileLoop + Thread.Sleep For Periodic Tasks

In my application I have to send periodic heartbeats to a "brother" application.

Is this better accomplished with System.Timers.Timer/Threading.Timer or Using a Thread with a while loop and a Thread.Sleep?

The heartbeat interval is 1 second.

while(!exit) {    //do work    Thread.Sleep(1000); } 

or

myTimer.Start( () => {                         //do work                        }, 1000); //pseudo code (not actual syntax)... 
like image 434
Alan Avatar asked May 12 '10 20:05

Alan


People also ask

Is system threading timer thread safe?

Timer is not thread-safe.

What is the difference between thread and timer?

As we see above, Thread is the implementation that does the heavy lifting, and Timer is a helper that adds extra functionality (a delay at the front); Timer(0, func) wouldn't work if Thread didn't exist.

What is System threading timer?

System. Threading. Timer, which executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed.

Does system timers timer run in a separate thread?

Yes, they run in a different thread.


1 Answers

System.Threading.Timer has my vote.

System.Timers.Timer is meant for use in server-based (your code is running as a server/service on a host machine rather than being run by a user) timer functionality.

A Thread with a While loop and Thread.Sleep command is truly a bad idea given the existance of more robust Timer mecahnisms in .NET.

like image 116
Justin Niessner Avatar answered Sep 25 '22 12:09

Justin Niessner