4

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?

SIMEL
  • 8,745
  • 28
  • 84
  • 130
  • 3
    Think about it this way. Suppose you wanted a reminder when it was time to watch Doctor Who on television. Would you hire someone whose job it was to sleep for 23 hours and 59 minutes a day, and then one minute of the day remind you that it's time for Doctor Who? And pay that guy for the full 24 hours of work? Because that's what you're doing in the latter technique. Threads are expensive. Don't hire a thread unless you have a lot of work for it to do. – Eric Lippert Mar 22 '13 at 05:07
  • check https://stackoverflow.com/questions/1416803/system-timers-timer-vs-system-threading-timer – rukoni Apr 16 '20 at 06:06

5 Answers5

4

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)
Sam Harwell
  • 97,721
  • 20
  • 209
  • 280
3

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    However, it should be noted that neither the timer events nor `Thread.Sleep` are guaranteed or expected to be precise in the first place. While a 100ms difference would be rare, `Thread.Sleep` can often vary by 10-20ms – Jason Watkins Mar 22 '13 at 01:59
  • @JasonWatkins You are right, it's worth mentioning that neither one of the two methods is especially precise. Thanks! – Sergey Kalinichenko Mar 22 '13 at 02:01
2

On a platform which offers you timers, I would always recommend you to use timers as they are probably implemented more efficient than with Thread.sleep. The problem is that sleep blocks the thread completely, wasting a whole thread just for the sake of notifying another thread.

A timer on the other hand can manage more than one time and just uses one thread. It may even use some extas the operating system offers. But not only that, it may even take some scheduling costs into account to be more precise (theoretically at least).

nemo
  • 55,207
  • 13
  • 135
  • 135
  • While technically correct, it shoud be noted that my Task Manager currently shows 1265 open threads. One more won't make any practical difference. – Jason Watkins Mar 22 '13 at 02:00
  • Just because you can be sloppy it doesn't necessarily mean that you should be :) – nemo Mar 22 '13 at 02:01
2

The only possible benefit might be off-loading to background thread. In your example, the timer's event handler will run on UI-thread while the latter will run on background thread.

I would use Task.Delay with async/await or ContinueWith method instead of Thread.Sleep though.

Soe Moe
  • 3,428
  • 1
  • 23
  • 32
  • The Forms timer running on the UI thread is a feature. A better solution for asynchronous timing would be to use `System.Timers.Timer` or `System.Threading.Timer`. – Jason Watkins Mar 22 '13 at 02:03
  • Yes. Agreed. I think he is asking what is benefit of using Task over Timer (Forms). And I think I mention that timer's event handler will run on UI-thread. :) – Soe Moe Mar 22 '13 at 02:05
  • And since Thread.Sleep will block the thread, he could use Task.Delay as non-blocking delay. Of course, if I can choose, I will just use `System.Threading.Timer`. – Soe Moe Mar 22 '13 at 02:07
1

No. There's absolutely no reason to use the second method.

Jason Watkins
  • 3,766
  • 1
  • 25
  • 39