Export (0) Print
Expand All

Reference Counting, Garbage Collection, and Object Lifetime

Visual Studio .NET 2003

Unlike COM, the common language runtime does not use reference counting to govern object lifetime. Instead, the garbage collector traces object references and identifies objects that can no longer be accessed by running code.

This simplifies component programming a great deal, because you do not have to worry about circular references. If a group of objects contain references to each other, but none of these object are referenced directly or indirectly from stack or shared variables, then garbage collection will automatically reclaim the memory.

An additional advantage of traced garbage collection is that allocation of new objects in memory is extremely fast. Performance is further improved by the elimination of the COM AddRef and Release mechanism, and objects require less memory.

The only potential disadvantage of traced garbage collection is the interval between the release of the last reference that can be reached by running code, and the moment when the garbage collector detects this condition. On a lightly loaded system with a great deal of memory, considerable time may elapse before your component's destructor is called.

The technique used in the .NET Framework is to implement a Dispose method on any component that uses limited or expensive system resources. When you are done using an instance of your component, you can call Dispose to free all resources except the memory the component is occupying, and to disable the component. For details, see Initialization and Termination of Components.

See Also

Component Architecture | Component.Dispose Method | IDisposable Interface

Show:
© 2014 Microsoft