Free mag vol1 | Page 542

CHAPTER 13  UNDERSTANDING OBJECT LIFETIME • Your application is about to enter into a block of code that you don’t want interrupted by a possible garbage collection. • Your application has just finished allocating an extremely large number of objects and you want to remove as much of the acquired memory as soon as possible. If you determine it could be beneficial to have the garbage collector check for unreachable objects, you could explicitly trigger a garbage collection, as follows: static void Main(string[] args) { ... // Force a garbage collection and wait for // each object to be finalized. GC.Collect(); GC.WaitForPendingFinalizers(); ... } When you manually force a garbage collection, you should always make a call to GC.WaitForPendingFinalizers(). With this approach, you can rest assured that all finalizable objects (described in the next section) have had a chance to perform any necessary cleanup before your program continues. Under the hood, GC.WaitForPendingFinalizers() will suspend the calling thread during the collection process. This is a good thing, as it ensures your code does not invoke methods on an object currently being destroyed! The GC.Collect() method can also be supplied a numerical value that identifies the oldest generation on which a garbage collection will be performed. For example, to instruct the CLR to investigate only generation 0 objects, you would write the following: static void Main(string[] args) { ... // Only investigate generation 0 objects. GC.Collect(0); GC.WaitForPendingFinalizers(); ... } As well, the Collect() method can also be passed in a value of the GCCollectionMode enumeration as a second parameter, to fine-tune exactly how the runtime should force the garbage collection. This enum defines the following values: public enum GCCollectionMode { Default, // Forced is the current default. Forced, // Tells the runtime to collect immediately! Optimized // Allows the runtime to determine // whether the current time is optimal to reclaim objects. } As with any garbage collection, calling GC.Collect()promotes surviving generations. To illustrate, assume that our Main() method has been updated as follows: 483