I know that c# allows to use a timer using:
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
timer.Interval = 1000/60;
timer.Tick += new EventHandler(TimerEventProcessor);
timer.Start();
private static void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{
//Do something
}
But, I have seen in this YouTube tutorial that instead of using Timer they created a thread that implements a timer of its own:
var task = new Task(Run());
task.start();
protected void run ()
{
while (true)
{
Thread.sleep(1000/60);
//Do something
}
}
Are there any benefits to using the second way over the simpler Timer?
There are timing methods that are better than System.Windows.Forms.Timer for various reasons, but none include your own thread management (that is a waste of resources since each thread has substantial memory overhead).
Comparing the Timer Classes in the .NET Framework Class Library
Here is the table from the bottom of the article:
+---------------------------------------+----------------------+---------------------+------------------+
| | System.Windows.Forms | System.Timers | System.Threading |
+---------------------------------------+----------------------+---------------------+------------------+
| Timer event runs on what thread? | UI thread | UI or worker thread | Worker thread |
| Instances are thread safe? | No | Yes | No |
| Familiar/intuitive object model? | Yes | Yes | No |
| Requires Windows Forms? | Yes | No | No |
| Metronome-quality beat? | No | Yes* | Yes* |
| Timer event supports state object? | No | No | Yes |
| Initial timer event can be scheduled? | No | No | Yes |
| Class supports inheritance? | Yes | Yes | No |
+---------------------------------------+----------------------+---------------------+------------------+
* Depending on the availability of system resources (for example, worker threads)
Although neither way of timing events is exact, the first method is somewhat more precise: consider a situation where the code that you marked with //Do something takes 100 ms. Then the interval between the invocations of //Do something would be 1000/60+100, not 1000/60 as you expected.
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