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)...
Timer is not thread-safe.
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.
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.
Yes, they run in a different thread.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With