9

I was coding a console application in C#, and my code was like this:

 while(true)
 {
 //do some stuff
     System.Threading.Thread.Sleep(60000)
 }

I noticed the memory usage of my application was about 14k while "sleeping". But then I referenced System.Windows.Forms and used a timer instead and I noticed huge drop in memory usage.

My question is, what is the proper way of making something execute every few seconds without using that much memory?

Tilak
  • 30,108
  • 19
  • 83
  • 131
method
  • 1,369
  • 3
  • 16
  • 29
  • 3
    Don't use `Thread.Sleep()` for timing purposes please. Its not accurate. – mishmash Jan 13 '13 at 16:18
  • 2
    [Here](http://msmvps.com/blogs/peterritchie/archive/2007/04/26/thread-sleep-is-a-sign-of-a-poorly-designed-program.aspx) is an interesting atricle on Thread.Sleep, to add to what vanneto said, combining Thread.Sleep with a while(true) loop will also result in high CPU usage, compared to a timer – JMK Jan 13 '13 at 16:29
  • 1
    FWIW `Thread.Sleep` is actually very accurate compared to any of the timers in the BCL. My tests show that `Sleep` is accurate to ~1ms with a stddev of 0.08ms. `System.Threading.Timer` on the other hand is only accurate to ~14ms with a stddev of 0.6ms. Mileage will vary. – Brian Gideon Oct 03 '13 at 02:34
  • Also, `Sleep` will not cause high CPU. In fact, on my machine with a timeout of 1 or higher calling `Sleep` in a tight loop will yield ~0% CPU usage. `Sleep(0)`, of course, will consume ~100% CPU usage. There are reasons for this as `Sleep(0)` and `Sleep(1)` have special meaning. – Brian Gideon Oct 03 '13 at 02:38

2 Answers2

12

You should use System.Timers.Timer

Add a method that will handle the Elapsed event and execute the code you want. In your case:

System.Timers.Timer _timer = new System.Timers.Timer();

_timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
_timer.Interval = 60000;
_timer.Enabled = true;

private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
   // add your code here
}

Here is a good post regarding the difference between the two Timers:

Community
  • 1
  • 1
chaliasos
  • 9,659
  • 7
  • 50
  • 87
4

You need to use Timer class.

There are multiple built-in timers ( System.Timers.Timer, System.Threading.Timer, System.Windows.Forms.Timer ,System.Windows.Threading.DispatcherTimer) and it depends on the requirement which timer to use.

Read this answer to get and idea of where which timer should be used.

Following is an interesting read.
Comparing the Timer Classes in the .NET Framework Class Library

Community
  • 1
  • 1
Tilak
  • 30,108
  • 19
  • 83
  • 131