【发布时间】:2012-06-17 03:47:42
【问题描述】:
我在 C# 中创建了一个控制台应用程序,并且有 main 方法(静态),我的要求是初始化 2 个计时器并分别处理 2 个方法,这些方法将被定期调用以执行某些任务。现在我已将所有其他方法/变量设为静态,因为它们是从计时器处理程序事件调用的(由于从 main 调用它是静态的)。
现在我想知道对于上述情况,如果这个控制台长时间运行,内存将如何消耗?如果我想应用 oops 概念,那么我是否需要将所有方法/变量设为非静态并通过创建类对象来访问它?在这种情况下,内存将如何消耗?
更新: 以下是我的代码的 sn-p
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
}
}
【问题讨论】:
-
不要把你的东西放在 Main。一般避免静态,除非你真的真的真的必须这样做。这是一种不好的做法。
标签: c# memory-management static console-application