I have created a console application in C# and there is main method (static) and my requirement is to initialize 2 timers and handles 2 methods respectively which will be called periodically to do some task. Now I have taken all other methods/variables static because that are calling from timer handler events (which are static due to calling it from main).
Now i would like to know for above scenario how memory is going to be consumed if this console running for long time? if i would like to apply oops concept then do i need make all methods/variables non static and access that by creating object of class? in this case how memory going to be consume?
Update: Following is snippet of my code
public class Program
{
readonly static Timer timer = new Timer();
static DateTime currentDateTime;
//other static variables
//-----
static void Main()
{
timer.Interval = 1000 * 5;
timer.AutoReset = true;
timer.Enabled = true;
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();
//2nd timer
//-----
System.Console.ReadKey();
timer.Stop();
}
static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
currentDateTime = DateTime.UtcNow;
PushData();
}
private static void PushData()
{
//Code to push data
}
}
You shouldn't be deciding whether or not to use static fields/methods based on memory consumption (which likely won't be altered much). Instead, you should go with what produces cleaner, more testable code.
Static methods are okay (IMO) if you don't need any kind of polymorphic behaviour, and if the method doesn't logically act on an instance of the type. However, if you've also got static variables involved, that's more of an issue. Static variables - other than constants - can make code much harder to test, reuse, and handle correctly in multiple threads.
It sounds like you probably should be using instance variables and methods. Just make your
Main
method create an instance of the class, and it can use that instance to create delegates to pass to the timer. It's hard to be much more precise than that without knowing more about what you're doing, but it does sound like you're using statics for immediate convenience rather than because it's the right thing to do, which is always a worry.