我正在创建一个程序,它将每 2 秒检查一次目录列表。我希望这个程序可以运行几个月而不会泄漏内存或需要任何人工交互。
下面的程序有内存泄漏。
我仍然不确定 10K 代表什么。这不是间隔。间隔为2k。
class Program
{
static void Main(string[] args)
{
Timer aTimer = new Timer(10000);
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 2000;
aTimer.Enabled = true;
Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine();
GC.KeepAlive(aTimer);
}
private static void OnTimedEvent(object source, ElapsedEventArgs e )
{
Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
string[] DirList = Directory.GetFiles(@"C:\TTImer");
if (DirList.Length > 0)
{
foreach (string s in DirList)
{
//do something
}
}
}
}