C# Timer and memory leak

前端 未结 3 466
既然无缘
既然无缘 2021-01-25 23:06

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.

3条回答
  •  北恋
    北恋 (楼主)
    2021-01-25 23:32

    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.

提交回复
热议问题