Background
When a program creates an object, the object takes up memory. Later, when
the program has no more references to the object, the object's memory
becomes unreachable but it is not immediately freed. Note also that the
object's Finalize event is not called at this point.
After a lot of memory has been "lost" to the program in this way, the
Garbage Collector may decide it's time to clean house. First it marks all of
the memory that has been used by objects as not in use. It then follows all
of the references that are accessible to the program and marks the objects
they refer to as in use. Finally, the Garbage Collector frees any objects
that are still not marked as in use. At this point, the Finalize methods for
those objects execute.
Normally you should leave the Garbage Collector alone. It usually does a
decent job of deciding when cleaning house will be worthwhile.
However, you may sometimes know something about the way the program works
that lets you know it would be helpful to perform garbage collection. For
example, suppose the program creates a huge number of objects, uses them for
a while, and then releases them. At that point, it might be worth reclaiming
the objects' memory so tou might force garbage collection. (Note: If you
don't force garbage collection, it will still occur later when the program
needs more memory.)
Method
When you click this program's Allocate Object button, the program creates a
new object. The button's Click event handler does not save a reference to
the object so it becomes eligible for garbage collection as soon as the
event handler exits.
|