Skip to Main Content
Programming .NET Components, 2nd Edition
book

Programming .NET Components, 2nd Edition

by Juval Lowy
July 2005
Intermediate to advanced content levelIntermediate to advanced
644 pages
17h
English
O'Reilly Media, Inc.
Content preview from Programming .NET Components, 2nd Edition

Object Finalization

.NET objects are never told when they become garbage; they are simply overwritten when the managed heap is compacted. This presents you with a problem: if the object holds expensive resources (files, connections, communication ports, data structures, synchronization handles, and so on), how can it dispose of and release these resources? To address this problem, .NET provides object finalization . If the object has specific cleanup to do, it should implement a method called Finalize(), defined as:

    protected void Finalize();

When the garbage collector decides that an object is garbage, it checks the object metadata. If the object implements the Finalize() method, the garbage collector doesn’t destroy the object. Instead, the garbage collector marks the object as reachable (so it will not be overwritten by heap compaction), then moves the object from its original graph to a special queue called the finalization queue . This queue is essentially just another object graph, and the root of the queue keeps the object reachable. The garbage collector then proceeds with collecting the garbage and compacting the heap. Meanwhile, a separate thread iterates over all the objects in the finalization queue, calling the Finalize() method on each and letting the objects do their cleanup. After calling Finalize(), the garbage collector removes the object from the queue.

Explicit Garbage Collection

You can trigger garbage collection explicitly with the static method Collect() of ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Windows Forms Programming in C#

Windows Forms Programming in C#

Chris Sells
Metaprogramming in .NET

Metaprogramming in .NET

Jason Bock, Kevin Hazzard
.NET Windows Forms in a Nutshell

.NET Windows Forms in a Nutshell

Ian Griffiths, Matthew Adams

Publisher Resources

ISBN: 0596102070Supplemental ContentErrata Page