C# Timer and memory leak

前端 未结 3 467
既然无缘
既然无缘 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:20
    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.

    0 讨论(0)
  • 2021-01-25 23:28
    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).

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题