This documentation is archived and is not being maintained.

Garbage Collection Sample 

Visual Studio 2005

Download sample

This sample shows some how to control the common language runtime (CLR) garbage collector. It demonstrates when the garbage collector calls any Finalize methods on created objects, as well as how to suppress finalization.

Security noteSecurity Note

This sample code is provided to illustrate a concept and should not be used in applications or Web sites, as it may not illustrate the safest coding practices. Microsoft assumes no liability for incidental or consequential damages should the sample code be used for purposes other than as intended.

To open the sample file in Solution Explorer

  1. Click Download Sample.

    The File Download message box appears.

  2. Click Open, and on the left column of the zip folder window, click Extract all files.

    The Extraction Wizard opens.

  3. Click Next. You can change the directory that the files will be extracted to, and then click Next again.

  4. Make sure that the Show extracted files check box is selected, and click Finish.

  5. Double-click the sample's .sln file.

    The sample solution is displayed in Solution Explorer. You might get a security warning that says the solution location is not trusted. Click OK to continue.

To run this sample

  1. Press F5.

  2. Close the application and note how any unfinalized objects are finalized as the form is closed.

Demonstrates

The buttons on the form execute code that allows you to manipulate the number of allocated objects, free objects, and garbage-collected objects.

  • Create Objects   This button creates a hierarchy of objects of the ListNode type, which is defined in the project.

  • Set Object to Nothing   This button releases the object selected in the lstCreatedObjects list box to garbage collection by setting it to Nothing.

  • Call Dispose   This button disposes of the object selected in the lstCreatedObjects list box. The IDisposable interface is implemented on the ListNode class.

  • Run Garbage Collector   This subroutine forces the garbage collector to run. The Collect method is not deterministic. That means that the operating system may delay running the garbage collector to finish some currently running tasks. In practice, you can expect the garbage collector to run within a second or so of the Collect method being called.

The sample also demonstrate garbage collector performance is improved on certain objects by using the SuppressFinalize method.

See Also

Show: