.NET中的垃圾收集器(Garbage Collector in .NET)

垃圾收集器如何知道对象和变量超出范围,以便垃圾收集器可以收集它们?

How does the garbage collector know the objects and variables are out of scope so they can be collected by garbage collector?

最满意答案

简而言之:每个应用程序都有一组根。 Roots标识存储位置,这些位置引用托管堆上的对象或设置为null的对象。

当垃圾收集器开始运行时,它假设堆中的所有对象都是垃圾。

垃圾收集器开始遍历根并构建从根可到达的所有对象的图形。

删除所有无法访问的对象(释放内存)

这取自http://msdn.microsoft.com/en-us/magazine/bb985010.aspx - 关于垃圾收集的好文章。 “有趣”的部分是“垃圾收集算法”。 这不是一个很长的部分

In short: Every application has a set of roots. Roots identify storage locations, which refer to objects on the managed heap or to objects that are set to null.

When the garbage collector starts running, it makes the assumption that all objects in the heap are garbage.

The garbage collector starts walking the roots and building a graph of all objects reachable from the roots.

All objects not reachable are removed (memory is freed)

This is taken from http://msdn.microsoft.com/en-us/magazine/bb985010.aspx - good article about the garbage collection. The "interesting" part for you is "The Garbage Collection Algorithm". It is not a very long section

更多推荐