. Net. GC

Source: Internet
Author: User
Tags comparison table

Developers familiar with. NET should know that there is a GC. Collect () in it. Its function is to forcibly recycle all generations of garbage. The following describes several related terms:

What is generation?

The generation refers to different regions in the managed memory. The older the object is located, the closer it is. For example, if an object is not recycled after the first garbage collection, it may be moved from generation 0 to generation 1, and so on.
What is garbage?

Spam means that there is no reference to any object and there is a reference to it. The major point is to find the reference from this object and keep searching. If you find that it is referencing a root, this is not garbage. If the root cannot be found, the object is garbage.

What is root?

A root is a storage location that contains a pointer to a reference type. For example, for static variables, the global variables are the root, the objects in the current Register are the root, and the parameters on the current call Stack are the root variables.

In addition, at the beginning of garbage collection, all the current threads will be suspended, start to collect the garbage from the managed stack, and compress the memory after collection, and then wait until the garbage collection ends before resuming these threads, from this perspective, garbage collection is still rarely called, but it is not adjustable, depending on the situation.

GC. Collect ()As shown in the following source code:

Dpformulalist. Clear ();
Dpformulalist = NULL;
Inputs. Clear ();
Inputs = NULL;
GC. Collect ();

 

Ease Article First, we need to clarify two concepts.
First, many people use. Net to write data. Program To talk about the concept of hosting. So what does. Net mean by resource hosting? Is it relative to all resources, or is it limited to some resources? Many people do not know this very well. . Net The hosting is only for memory, not for all resources; therefore, for stream , Database connection, GDI + And com. Objects. These resources are not affected by. net. Management. For memory release and recovery, the system provides GC-Garbage Collector Other resources must be manually released.

In my previous articles, I learned that the. NET type is divided into two categories: Value Type and reference type. The former is allocated to the stack and does not require GC collection; the latter is allocated to the stack. Therefore, the memory release and recovery must be completed through GC. GC is called "Garbage Collector". As its name implies, it is a garbage collector. Only objects called garbage can be recycled by GC. That is to say, The memory occupied by a reference type object needs to be GC Garbage collection is required first. So. net How can I determine that a reference type object is spam?. net As long as it is determined that this object or its contained Sub-objects are not referenced by any reference, the system considers it as garbage.

After clarifying these two basic concepts, let's talk about how GC works and its functions. The release and recovery of memory must be accompanied by program running. Therefore, the system schedules independent threads for GC. GC generally queries whether objects in the memory become garbage and then releases and recycles the garbage. Therefore, GC takes priority over memory recovery.Algorithm To recycle memory resources. Second, There are two types of garbage in the memory: one is to call the destructor of the object, and the other is not to call. GC The collection of the former requires two steps. The first step is to call the object's destructor, and the second step is to recycle the memory, but note that these two steps are not performed in the GC Two rounds are required for one round robin. Compared with the latter, the memory is only recycled.

It is clearly known that for a specific resource, you cannot know exactly when the object destructor will be called, and when the GC will release and recycle the memory it occupies. For programmers who have switched from languages such as C and C ++, the concept should be changed here.

So for program resources, what should we do and how to do it, in order to make the program more efficient, while occupying resources can be released as soon as possible. As mentioned above, there are two types of resources: managed memory resources, which do not require us to worry about. The system has already managed for us. For unmanaged resources, here we reiterate that stream, database connection, related objects of GDI +, and COM objects need to be manually released.

How should we release these operations .. NET provides three methods, which are also the most common, roughly as follows:
<! -- [If! Supportlists] --> 1. <! -- [Endif] --> destructor;
<! -- [If! Supportlists] --> 2. <! -- [Endif] --> inherits the idisposable interface and implements the dispose method;
<! -- [If! Supportlists] --> 3. <! -- [Endif] --> provides the close method.

After the previous introduction, we can know that the Destructor can only be GCSo it is not reasonable to use it as a resource release because the resource release is not timely; but to prevent resource leakage, after all, it will be GCSo the Destructor can be used as a remedy. CloseAnd disposeThe difference between the two methods is that the close of the object is called.This object may be re-used; and DisposeMethod, the resources occupied by this object need to be marked as useless, that is, the object is destroyed and cannot be used again.For example, for the common sqlconnection class, after the close method is called, you can re-open the database connection through open. When this object is completely unnecessary, you can call the dispose method to mark this object as useless, wait for GC collection. After understanding the meaning of the two methods, do not distort the meaning of the two methods when you add interfaces to your own classes.

Next, let's talk about the call times of these three functions. I will explain them with a few experimental results, which may bring you a deeper impression.
The first is the implementation of these three methods, which are roughly as follows:

/// <Summary>

/// The class to show three disposal function

/// </Summary>

Public class disposeclass: idisposable

{

Public void close ()

{

Debug. writeline ("Close called! ");

}

~ Disposeclass ()

{

Debug. writeline ("destructor called! ");

}

# Region idisposable members

Public void dispose ()

{

// Todo: Add disposeclass. Dispose implementation

Debug. writeline ("dispose called! ");

}

# Endregion

}

For close, it is not a release in the true sense. Except that it needs to be displayed and called, I will not talk much about it here. The Destructor is not executed immediately after the object leaves the scope. It is called only when the process is disabled or the GC. Collect method is called. See the followingCodeRunning result.

Private void create ()

{

Disposeclass myclass = new disposeclass ();

}

Private void callgc ()

{

GC. Collect ();

}

// Show destructor

Create ();

Debug. writeline ("after created! ");

Callgc ();

The running result is:

After created!

Destructor called!

Apparently, except for the create function, The destructor of the myclass object is not called immediately, but is called only when GC. Collect is called.

For dispose, you also need to display the call, but for type objects that inherit idisposable, you can use the Using Keyword, so that the dispose method of the object will be automatically called after the using range exists. For example:

Using (disposeclass myclass = new disposeclass ())

{

// Other operation here

}

The running result is as follows:
Dispose called!

For the above disposeclass implementation, GC also needs to call the object's destructor,Follow the preceding stepsGCFor the process, GCFor an object that needs to call the destructor, at least two steps are taken, that is, the object's destructor is called first, and the memory is recycled. That is to say, according to the disposeFunction, although executed, but GCStill need to execute the destructor, then a complete disposeFunction, you should call GC. suppressfinalize (this)To tell GCSo that it no longer needs to call the object's destructor.The modified disposeclass is as follows:

/// <Summary>

/// The class to show three disposal function

/// </Summary>

Public class disposeclass: idisposable

{

Public void close ()

{

Debug. writeline ("Close called! ");

}

~ Disposeclass ()

{

Debug. writeline ("destructor called! ");

}

# Region idisposable members

Public void dispose ()

{

// Todo: Add disposeclass. Dispose implementation

Debug. writeline ("dispose called! ");

GC. suppressfinalize (this );

}

# Endregion

}

Use the following code for testing.

Private void run ()

{

Using (disposeclass myclass = new disposeclass ())

{

// Other operation here

}

}

Private void callgc ()

{

GC. Collect ();

}

 

// Show destructor

Run ();

Debug. writeline ("after run! ");

Callgc ();

The running result is as follows:

Dispose called!

After run!

 

Obviously, the object's destructor is not called. Through the above experiment and text instructions, you will get the following comparison table.

 

Destructor

Dispose Method

Close Method

Meaning

Destroy object

Destroy object

Disable object Resources

Call Method

Cannot be displayed and called by GC

Call to be displayed

Or use the using statement.

Call to be displayed

Call time

Uncertain

Are you sure you want to call or exit the using block?

OK.

When defining a type, do you have to implement these three functions.

My suggestions are as follows.

1.Provides destructor to prevent resources from being released, mainly non-memory resources;

2.For the dispose and close methods, you need to check the resources used by the defined types (see the previous descriptions) and decide whether to define these two functions;

3.When implementing the dispose method, you must add the "GC. suppressfinalize (this)" statement to avoid GC calling the object's destructor.

 

C # The memory used by the program is hosted, but it does not mean abuse. Good Programming habits are conducive to improving the code quality and program running efficiency.

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.