Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do timers work in .NET?

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?

like image 567
method Avatar asked Jan 13 '13 16:01

method


2 Answers

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:

  • SO: System.Timers.Timer vs System.Threading.Timer
like image 63
chaliasos Avatar answered Sep 22 '22 06:09

chaliasos


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

like image 45
Tilak Avatar answered Sep 21 '22 06:09

Tilak