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?
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
:
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
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