处置后多久可以使用内存?

时间:2015-06-15 13:05:15

标签: c# winforms user-controls garbage-collection

GC运行后是否瞬间完成?

我在运行我正在处理的应用程序时使用perfmon监视内存(可用MBytes)。当我加载文件时,我可以看到可用MBytes按预期下降,但当我关闭它时它没有恢复,所以我想知道我是否没有正确处理或者是否有其他影响此

加载文件时:

  • 内容存储在一些对象中
  • 创建UserControl的新实例
  • 创建了一个新的TabPage
  • UserControl已添加到TabPage
  • TabPage已添加到TabControl

阅读SO我发现可能导致内存泄漏的最常见的事情之一不是取消订阅事件处理程序,所以我确保在UserControl的dispose方法中这样做。我订阅了#Removing; RemovingTab' TabControl的事件,但TabPages本身没有附加的处理程序。

关闭文件时,我删除了存储的对象实例,并在UserControl和TabPage上调用dispose。我尝试运行CLR分析器(我没有任何经验)并且它说没有GC运行。

2 个答案:

答案 0 :(得分:0)

另一个未被释放的常见内存源是保留非托管资源,打开文件就是一个例子。

GC清理正在使用的内存后,内存可用。并非每次GC运行都会导致内存被释放。任何幸存至少一次GC运行的对象都可能会长时间存活,因为它不再是第0代 - 这些可能最终会出现,直到应用程序实际需要的内存比目前可用的内存多。大对象(大约85kb,据我记得)存储在大对象堆上,这也不是每次GC运行的一部分。

你最好的选择是看看实际上持有记忆的是什么。使用Visual Studio性能工具或尝试PerfView。一旦你知道实际拥有内存的是什么,你就会更好地了解如何释放内存。

答案 1 :(得分:0)

Is it instantaneous after the GC runs?

No. As a matter of fact, depending on the memory pressure of your particular application, the GC might not free up any memory during the whole lifespan of your application.

Reading on SO I saw that one of the most common things that can cause Memory Leaks is not unsubscribing from event handlers and so I made sure I did that in my UserControl's dispose method.

Yes that is a common cause.

When closing a file, I remove stored instances of the objects and call dispose on both the UserControl and the TabPage. I tried running the CLR profiler (which I haven't had any experience with) and it said there was no GC runs.

The GC is very good at doing what it's supposed to do and it has been fined tuned to extremes. If it doesn't run its probably because it has decided that it doesn't need to run. Therefore, when the memory is freed up by the GC is up to the GC to decide and, if I'm not mistaken, is implementation defined, so it is not something you can rely upon.

And last but not least, the IDisposable pattern is not, by any means, a deterministic pattern for reclaiming memory; that is most definitely not the pattern's goal.