C#计时器和内存泄漏 [英] C# Timer and memory leak

查看:170
本文介绍了C#计时器和内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个程序,该程序每2秒检查一次目录列表.我希望该程序可以运行几个月,而不会泄漏内存或需要任何人为干预.

I am creating a program that will check for directory listing every 2 seconds. I expect this program to run for months without leaking memory or requiring any human interaction.

  1. 下面的程序存在内存泄漏.

  1. Below program has memory leak.

我仍然不确定10K代表什么.不是间隔.间隔是2k.

I am still not sure what the 10K represents. It is not the interval. The interval is 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
            }
        }
    }
}

推荐答案

  1. 否,没有内存泄漏,这是使用垃圾收集器的语言中程序的预期行为.内存将增加,直到最终达到垃圾收集器清理所有不需要的对象的程度.

  1. No, there is no memory leak, that is the expected behavior of a program in a langauge that uses a garbage collector. The memory will increase until eventually it hits a point where the Garbage Collector cleans up any unneeded objects.

在这里可以指定计时器的间隔.您稍后将对其进行覆盖,因此此操作无济于事.

It's a place to specify the timer's interval. You're overwriting it later on, so this is accomplishing nothing.

这篇关于C#计时器和内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆