Section 13th: Programming Control garbage collector

Source: Internet
Author: User

The System.GC type allows the application to control garbage collection in some way directly. For example, you can read the Gc.maxgeneration property to query the maximum algebra supported by the managed heap; The property always returns 2.

You can also invoke the following static method to force a garbage collection:

public static void Collect ();

public static void Collect (int generation);

public static void Collect (int generation, gccollectionmode mode);

The second method allows you to specify which generation to recycle, passing 0 leading to No. 0 generation Recycling, passing 1 leading to 1th generation and No. 0 generation recycling, delivery 2 leading to 2nd generation, 1th generation, No. 0 generation recycling. An argument-free version causes a collection to be performed on all generations.

The third overloaded version of the method allows a generation and a gccollectionmode to be passed. The following summarizes the various GC recycle pattern symbols.

GCCollectionMode the symbols defined by the enumeration:

Default: Equivalent to not passing any symbol names. Currently also equivalent to passing forced, but future versions of the CLR may be modified

Forced: Forced collection of the specified generation (and less than its generation)

Optimized only performs recycling if it can release large amounts of memory or reduce the amount of fragmentation. If the garbage collection is not performing well, the current call has no effect.

In most cases, you should avoid calling any of the collect methods; it is best to have the garbage collector do it at your own discretion and adjust the budget for each generation based on the behavior of the actual application. However, if you want to write a Cui (console user interface) and GUI (graphical user interface) application, The application code will own the process and the CLR in that process. For this application, you might recommend that a garbage collection occur at a specific time; To do this, set GCCollectionMode to optimized and call collect. In general, both the default and forced modes are for debugging and testing purposes.

For example, if a non-recurring event has just occurred and a large number of old objects die, consider calling the Collect method manually. For non-repeatable events, the garbage collector may not be accurate in its future predictions based on history. So it is appropriate to call the Collect method in this case.

For example, after the application initialization is complete, or after the user has saved a data file, the application is appropriate to enforce a garbage collection on all generations. When a window form is hosted on a Web page, each time a page is unloaded, a full garbage collection is performed, and the call to collect method is not displayed to improve the response time of the application, and it should only be called for the purpose of reducing the working set of the process.

The GC class also provides a WaitForPendingFinalizers method. The method suspends the calling thread until the thread that handles the freachable queue empties the queue, completing the call to the Finalize method for each object. It is not necessary to call this method in most applications, but I have seen the following code:

Gc. Collect ();

Gc. WaitForPendingFinalizers ();

Gc. Collect ();

The above code forces the start of a garbage collection. After the collection is complete, the memory of the object that does not need to be finalized is recycled. But the memory of the object that needs to be terminated is not yet recycled. After the first collect call returns, the thread that is specifically responsible for the finalization operation calls the Finalize method asynchronously. A call to the WaitForPendingFinalizers method puts the application thread to sleep. Until all Finalize method calls are complete. After the WaitForPendingFinalizers method returns, all objects that are terminated are garbage. At this point, the second collect call forces the start of another garbage collection, which reclaims the garbage.

For some applications (especially server applications that prefer to hold a large number of objects in memory), it may take too long to perform a full garbage collection of objects that contain the 2nd generation. If a collection takes a long time to complete, the client request may time out. To accommodate the needs of this application, the GC class provides a registerforfullgcnotification method. Using this method and some additional auxiliary methods (WaitForFullGCApproach, WaitForFullGCComplete, cancelfullgcnotification) The application receives a notification when the garbage collector is about to perform a garbage collection. The application can then invoke Gc.collect to enforce a collection at a more appropriate time. The application can also communicate with another server to better load-translate requests from clients.

Finally, the GC class provides two static methods to help you determine which generation the object is currently in:

int Getgeneration (object obj);

int getgeneration (WeakReference wo);

The first version is to get an object reference as a parameter, and the second version is to get the WeakReference reference as a parameter. The two methods return a value of 0 to Gc.maxgeneration.

The code helps to understand how the generation works:

Sealed class Genobj

{

~genobj ()

{

Console.WriteLine ("In Finalize method");

}

}

Class Program

{

static void Main (string[] args)

{

Console.WriteLine ("Maximun Generation:" + GC. Maxgeneration);

Object o = new Genobj ();

Console.WriteLine ("Gen" + GC. Getgeneration (o));//0

Perform a garbage collection promotion object generation

Gc. Collect ();

Console.WriteLine ("Gen" + GC. Getgeneration (o));//1

Gc. Collect ();

Console.WriteLine ("Gen" + GC. Getgeneration (o));//2

Gc. Collect ();

Console.WriteLine ("Gen" + GC. Getgeneration (o));//2

o = null;

Console.WriteLine ("Collecting Gen 0");

Gc. Collect (0);//recovery of the No. 0 generation

Gc. WaitForPendingFinalizers ();//finalize not called

Console.WriteLine ("Collection gens 0, and 1");

Gc. Collect (1);//recovery of No. 0 and 1th generation

Gc. WaitForPendingFinalizers ();//finalize not called

Console.WriteLine ("Collection gens 0, 1 and 2");

Gc. Collect (2);

Gc. WaitForPendingFinalizers ();//finalize call

}

}

Section 13th: Programming Control garbage collector

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.