Condividi tramite


Garbage Collection Technology Sample

This sample introduces developers to garbage collection in the .NET Framework and shows design features of classes that work well in a garbage-collected environment. The sample also shows how an application can control some of the garbage collector's behavior, for example, in forcing collections, promoting objects, and working with weak references to objects.

For information about using the samples, see the following topics:

To build the sample using the Command Prompt

  1. Open a Command Prompt window and navigate to one of the language-specific subdirectories under the GarbageCollection directory.

  2. Type msbuild GarbageCollectionCS.sln or msbuild GarbageCollectionVB.sln at the command line, depending on your choice of programming language. For example, in the directory C:\Documents and Setttings\Your User Name\My Documents\Samples\Technologies\GarbageCollection\VB, type msbuild GarbageCollectionVB.sln to build the Visual Basic version.

To build the sample using Visual Studio

  1. Open Windows Explorer and navigate to one of the language-specific subdirectories under the GarbageCollection directory.

  2. Double-click the icon for GarbageCollectionCS.sln or GarbageCollectionVB.sln, depending on your choice of programming language, to open the file in Visual Studio 2005.

  3. On the Build menu, click Build Solution.

To run the sample

  1. Open a Command Prompt window and navigate to the directory that contains the new executable.

  2. Type GarbageCollection.exe at the command line.

    NoteNote

    The sample is a console application. You must launch it from the command line in order to view its output.

Requirements

.NET Framework Version: 2.0, 1.1, 1.0

Remarks

In the managed runtime environment, the garbage-collected heap manages all class objects. This heap monitors the lifetime of objects and frees them only when no part of the program references the objects. This ensures that objects never leak memory and that references to objects are always valid. In order to demonstrate that finalization occurs on a special thread, the sample employs the Thread class to retrieve the hash code of threads. It reveals that the hash code returned by a normal method call has a different value than one returned during finalization.

Within the source code, the sample references the System.Threading namespace to retrieve the hash code values for the respective threads on which the application methods and the garbage collection run.

See Also

Reference

Dispose
Finalize
GC
System.Threading
Thread
WeakReference

Other Resources

Garbage Collection