Game Development Reference
Another useful operation is the GC.WaitForPendingFinalizers method that suspends
the calling thread until the finalization thread has emptied the f-reachable queue
and all finalizers have been executed. It is uncommon that you should need to call
this method directly unless you know what you are doing.
Aside from statistics like GC.MaxGeneration that returns the maximum number of
generations, you can query any object or WeakReference to determine the genera-
tion that it is currently stored in.
Int32 GetGeneration(Object obj)
Int32 GetGeneration(WeakReference weakRef)
The value returned will be inclusively within the range of 0 and GC.MaxGeneration .
This chapter covered many aspects of the garbage collector intrinsic to the .NET
platform, along with ways to optimize your allocation profile and program flow to
increase performance and responsiveness. First, you were introduced to a high-
level overview of the garbage collector and the purposes that it serves. Then the
discussion became low-level and centered on everything that goes on behind the
scenes. A number of rules and best practices were mentioned, along with some
warnings about possible trouble spots.
Techniques for profiling the allocation profile of your application were also cov-
ered, as well as techniques to properly release unmanaged resources that require
While fairly comprehensive, this chapter did not cover absolutely everything about
the .NET garbage collector. The purpose of this chapter was not for you to walk
away with an intimate knowledge of how the GC works, but rather with the
knowledge to develop your applications to take advantage of automated memory
management without suffering much of a performance hit. Some things that were
not covered include the AddMemoryPressure and HandleCollector mechanisms that
were introduced in .NET 2.0.
Automated memory management is a wonderful benefit to using the .NET plat-
form for tools development due to the increased stability and reliability. The
garbage collector will never go away, so learning the specifics of what goes on
behind the scenes will make development and optimization much more straight-