C# Timer and memory leak

2019-03-04 17:56发布

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. Below program has memory leak.

  2. 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
            }
        }
    }
}

3条回答
劳资没心,怎么记你
2楼-- · 2019-03-04 18:29

If one were being billed for every second that a megabyte of memory was being used needlessly, then it might make sense to worry about the fact that useless objects may survive quite awhile without being garbage-collected. In practice, though, leaving memory allocated needlessly will have no effect unless or until there is some other purpose to which that memory could otherwise be put. A typical garbage collector may be viewed as as a process that goes through a building, finds everything of value and moves it to another building, and then dynamites the first building and creates a new empty one. The cost of that operation will depend mainly upon the amount of stuff that has to be kept, and will be largely independent of the amount of junk that gets destroyed. Thus, unless there's something else useful that could the memory, the cost per megabyte of junk will be minimized if lots of junk is allowed to pile up before it is destroyed wholesale. For various reasons, even if there were only one program in the system and one had four gigs of memory to run it, it would generally be a good idea to perform garbage-collection cycles before multiple gigs of junk had accumulated, but unless there are other things that need to use the memory, overly-aggressive garbage collection would impair rather than improve efficiency.

查看更多
祖国的老花朵
3楼-- · 2019-03-04 18:48
  1. I am going to assume that you believe there is a leak because your task manager mem usage is going up (which is completely normal). The virtual memory manager is lazy and won't swap out anything unless it needs to. Your GC will clean up anything once a threshold is hit.

  2. The 10000 value is the specified timer interval in milliseconds. As Servy pointed out, you're overwriting it later on so you're accomplishing nothing except maybe getting rid of warnings upon building the project (e.g. uninstantiated object).

查看更多
smile是对你的礼貌
4楼-- · 2019-03-04 18:52
  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.

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

查看更多
登录 后发表回答