method
method

Reputation: 1389

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?

Upvotes: 9

Views: 8677

Answers (2)

Tilak
Tilak

Reputation: 30728

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

Upvotes: 4

chaliasos
chaliasos

Reputation: 9793

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:

Upvotes: 12

Related Questions