我在C#中創建了一個控制檯應用程序,並且有main方法(靜態),我的要求是分別初始化2個定時器和處理2個方法,這些方法將被定期調用以執行某個任務。現在我已將所有其他方法/變量都設爲靜態,因爲它們是從定時器處理程序事件(由於從main調用它而爲靜態的)調用的。我應該去靜態方法還是非靜態方法?
現在我想知道上面的情況如果這個控制檯運行很長時間如何消耗內存?如果我想應用oops概念,那麼我是否需要使所有方法/變量非靜態並通過創建類的對象來訪問它?在這種情況下,內存將如何消耗?
更新: 以下是我的代碼片段
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
}
}
不要把你的東西放在主。一般情況下避免靜態,除非你真的真的必須這樣做。這是一個不好的做法。 – SimpleVar