C # garbage collection,

Source: Internet
Author: User
Tags finally block

C # garbage collection,

Structure Method:

We know that all reference types have constructor, and there is also a corresponding destructor ). as the name implies, the constructor is the method to be executed when this object is created. For example, we can use the constructor,

Initialize fields. The Destructor is the method to be executed when the object is reclaimed (garbage collected, we call the recycle object memory as the garbage collection. For the destructor, you should note that garbage collection is not completed by the Destructor (the working principle of garbage collection will be discussed below ), the Destructor can only be executed after the object is recycled. That is to say, the Destructor is not necessary for an object. Most of the time, if you add it, it is not good (The following describes how garbage collector works, you will understand the cause ).

Since garbage collection is not the responsibility of the destructor, what is the purpose of garbage collection? Because garbage collection is automatically executed by CLR, CLR can only process managed resources.

I handled it myself. For example, when the object ends, we need to turn off the file stream. The code for turning off the file stream should be in the destructor. That is to say, the use of the Destructor is more useful when processing resources that are not managed.
Let's look at an example:

class FileProcessor{     FileStream file=null;
Public FileProcess (string fileName) {this. file = file. OpenRead (fileName); // open file for reading }~ FileProcess () // The Destructor is similar to the constructor. The difference is that one ~ {This. file. Close (); // close file }}

The file object is CRL garbage collection. When the file is garbage collection, run the Destructor FileProcess. In this case, we disable the unmanaged resources. This. file. Close ().

There are several restrictions on the Destructor:

1. Only the reference type can have the destructor.

Struct MyStruct (){~ MyStruct () {...} // The structure is of the value type, so there is no destructor}

2. Access modifiers cannot be provided for the destructor.

Public ~ FileProcessor () {}; // incorrect

3. The Destructor cannot have parameters.

~ FileProcessor (int param) {... // incorrect };

These three restrictions are imposed because the Destructor can only be called by CLR and cannot be called by itself. Because you don't know when the referenced object will be reclaimed. The program will call the Destructor only when the object is reclaimed.

Internally, the program will convert the structure method we wrote. For example:

Class FileProcessor {~ FileProcessor (){...} // destructor} class FileProcessor {protected override void Finalize () {try {} finally {base. finalize (); // CLR converts the destructor to this }}}

The process of executing the Destructor is called finalization or termination .)

 

Garbage collector)

As we mentioned above, the process of reclaiming memory space and unwanted reference objects is called garbage collection. This process is run by CLR through a mechanism such as Garbage collector.

When we create a variable in the program, it will open up a space in the memory. The computer memory is not infinitely large. We need to manage the memory occupied by the variable beyond the defined range (the program no longer needs this variable) and process the memory. When a variable is no longer used, the memory needs to be recycled. The Value Type Variable recycles memory, which is very simple.

When it exceeds the defined range, it will be destroyed automatically, and the Occupied memory will be recycled automatically. Beyond the defined range, it means that when it is no longer used and cannot be used again. The reference type variable recycles memory, which is troublesome. For example:

fileProcessor myFp=new fileProcessor();fileProcessor referenceToMyFp=myFp;


In this case, the myFp object has exceeded the defined range. In this case, we need to recycle the memory on the myFp reference stack. However, at this time, referenceToMyFp is still referencing the memory to be recycled. If the memory is recycled at this time, when the program runs referenceToMyFp, an error will occur. Therefore, the memory referenced by these objects can be recycled only when all referenced objects are out of the defined range, that is, they are no longer used. It is very difficult and complicated to ensure that all the referenced objects in the program pointing to the same part are not used. therefore, the C # designer handed over the processing of the reference type to the CLR (Common language running ). CLR uses the garbage collector mechanism to handle these issues.

Working principle of the garbage collection mechanism

Garbage collector works in its own thread and is executed at a specific time. Generally, it works when the program runs to the end of a method. When it works, other threads temporarily stop working. Because garbage collector may remove or update object references.

1. garbage collector creates a table that stores all the available objects (reachable objects ,. objects that are still in use and cannot be recycled .).

2. Check the unreachable objects that are out of the defined range and need to recycle the memory. (Destructor), put these objects into

Freachable queue.

3. Reclaim the memory address pointed to by objects that cannot get objects and do not have the destructor. It moves down the addresses of available objects on the stack so that available memory is reserved on the stack. The garbage collector also updates the heap.

. (Because the address is changed ).

4. At this time, other threads in the program resume work.

5. garbage collector calls its Finalize method to end objects with non-existent destructor. (As we mentioned earlier, the Destructor are not necessary and sometimes complicated and cumbersome to the program. If there is no destructor, when

When CLR runs Garbage collector, you can skip step 5 ).

 

Resource management

Some resources are scarce, so they cannot wait until the CLR calls the Destructor for processing. For example, database connections and file handles. At this time, we need to write a dispose method to manually process resources. (Dispose can be changed to any name.

For example ). For example:

TextReader reader=new StreamReader(filename);string line;while((line=reader.ReadLine())!=null){     Console.WriteLine(line);}reader.Close();

Here, Close is a dispose method. manually Close the file stream. However, in this case, when an exception occurs, reader. Close () may not be executed, so that resources are always occupied. Therefore, we need to rewrite it:

TextReader reader=new StreamReader(filename);try{    string line;    while((line=reader.ReaderLine())!=null){      Console.WriteLine(line);}}finally{   reader.Close();}

In this way, reader. Close () will be executed and resources will be released. However, even if it is rewritten like this, it is not perfect. Because when we execute the finally block code, that is, after try finally, we may

The unintentional use of the reader object is the reader object after the resource is released. In this case, we can use the using statement to solve these problems. After we change the above Code to using:

using(TextReader reader=new StreamReader(filename)){    string line;    while((line=reader.ReadLine())!=null){        Console.Writle(line);}}

After the using is executed, the resource is automatically released, beyond the using range, and the object cannot be used. To support using, an object must implement the IDispose interface.

We create a class by ourselves and inherit the IDispose interface so that it can be used in USING statements. Here we should distinguish the Destructor from the dispose method. We know that the Destructor will be executed, but we don't know when to execute it. We

I know when the dispose method will be executed, but I don't know if it will be executed. Because there is a dispose method in the class, it doesn't necessarily mean that this class will be used in the using statement. In this case, we can call the dispose method through the destructor.

To ensure that the dispose method is called.

Related Article

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.