Analysis of memory management mechanism

Source: Internet
Author: User

In the. NET Framework, resources in memory, which is a collection of all binary information, are classified as managed resources and unmanaged resources. Managed resources must accept the management of the CLR (Common Language Runtime) of the. NET framework, such as memory type security checks.  Instead of hosting resources, you do not have to accept the CLR management of the. NET Framework. (For more information, see the. NET Framework or advanced programming materials for C #)

Managed resources are stored in two places in the. NET framework: Stacks and managed heaps (the "heap"); The rule is that all value types (including references and object instances) and reference types are stored in the stack, and all references represent instances of the objects that are stored in the heap.

In C #, releasing managed resources can be done automatically through the garbage collector (note that the "garbage collection" mechanism is a feature of the. NET framework, not C #), but there are still some things to keep in mind:

1. Value types (including references and object instances) and reference type references actually do not require any "garbage collector" to free up memory, because when they are scoped, they will automatically free up the occupied memory (because they are stored in the "stack", learning the data structure that this is an advanced post-out structure);

2. Only the object instance pointed to by a reference type reference is saved in the heap, and the heap is not a free storage space, so it does not have a lifetime like "stack" (the "stack" element pops up to the end of the lifetime, which means that the memory is freed), and it is important to note that the "garbage collector" Only works on this area;

3. The "garbage collector" may not be executed immediately as many people think (when resources in the heap need to be freed), but rather when a reference to a reference type is deleted and the object instance in the heap is deleted in the middle of the interval. Because the "garbage collector" calls are relatively consuming system resources, it is not always possible to be called!

(Of course, user code can use method System.GC.Collect () to enforce the "garbage collector")

However, in most cases, we need to explicitly release the managed resources without executing the garbage collector (because only some of the resources that need to be freed are freed, but it is best not to call the garbage collector, because the garbage collector is too wasteful of system resources), or you need to release unmanaged resources. What do we do at this time? This is what we have to consider when writing code (the "garbage collector" is automatically implemented by the system, the general situation does not require user intervention), or the Windows system because of memory exhaustion and ...

Now, what I'm going to tell you is that using the Dispose () method of the class frees all types of resources and frees unmanaged resources using a destructor!

1.Dispose () method

To free up resources through the Dispose () method, use the "System.IDisposable" interface when the class is defined, and then you must include the method defined in the class "void Dispose ()" (in the Dispose () Method is the code snippet that the user writes to release the resource, so the user knows that the resource can be freed by invoking the Dispose () method artificially. However, it is important to note that the garbage collector does not release managed resources by calling the Dispose () Method!

2. Destruction methods

The format for defining the destructor method in C # is "~class_name ()". It is important to note that if an unmanaged resource is not used in a class, you must not define a destructor because the object performs a destructor, and the garbage collector calls the destructor before releasing the managed resource , and then the second time to really release the managed resources, so that two delete actions more than once! (However, even if you already have a destructor defined in your class, there is still a way to "mask" it, as explained in the following code example), in the Destructor method, the code snippet that the user wrote to release the unmanaged resource.

Here's a piece of code to demonstrate how the Dispose () method and the Destructor method are used:

 Public classResourceHolder:System.IDisposable { Public voidDispose () {Dispose (true); System.GC.SuppressFinalize ( This); //The previous line of code is to prevent the garbage collector from calling methods in this class//"~resourceholder ()"//Why should it be prevented? Because if the user remembers to call the Dispose () method,//The "garbage collector" has no need to "superfluous" the "unmanaged Resources" again.//If the user does not remember the call, let the "garbage collector" help us to "superfluous" it ^_^
//you do not understand what I said above does not matter, below I also have a more detailed explanation! } protected Virtual voidDispose (BOOLdisposing) { if(disposing) {//This is the user code snippet that cleans up the "managed resources" } //here is the user code snippet to clean up Unmanaged resources } ~Resourceholder () {Dispose (false); } }

The above code is a typical class definition with two Dispose methods.

There are many system classes in the. NET framework that define the Dispose () method in this way, for example:

In MSDN, the System.Drawing.Brush.Dispose method is defined like this:

************************************************************

* Releases all resources used by this Brush object. *

* public void Dispose () *

* This member supports the. NET framework structure and is therefore not intended to be used directly from your code. *

* Protected virtual void Dispose (BOOL); *

************************************************************

Here, we have to be clear that the user is required to call the method Dispose () instead of the method Dispose (bool), however, the method that actually performs the release work here is not Dispose (), but Dispose (bool)! Why not? Look closely at the code, in Dispose (), call Dispose (true), and the argument is "true" when the function is to clean up all the managed and unmanaged resources; You remember before I said, "The use of destructors is used to release unmanaged resources", So since Dispose () can do the work of releasing unmanaged resources, what do you do with the destructor method? In fact, the function of the destructor is only a "backup"!

Why is it?

Strictly speaking, where the class that executes the interface "IDisposable", so long as the programmer in the code to use the object instance of this class, then sooner or later call this class's Dispose () method, at the same time, if the class contains the use of unmanaged resources, you must also release the unmanaged Resources! Unfortunately, if the code that frees the unmanaged resource is placed in the destructor (the example above corresponds to "~resourceholder ()"), then it is impossible for the programmer to invoke the release code (because the destructor cannot be called by the user, but only by the system, which is called the "garbage Collector"). So you should know why the "user code snippet to clean unmanaged resources" in the example above is in Dispose (bool), not ~resourceholder ()! Unfortunately, not all programmers are always careful to call the Dispose () method, in case the programmer forgets to call this method, the managed resource is certainly no problem, sooner or later there will be a "garbage collector" to recycle (just a little later), then unmanaged resources? It is not controlled by the CLR! Is it that the unmanaged resources it occupies will never be released? Of course not! We also have "destructor"! If you forget to call Dispose (), the garbage collector also calls the Destructor method to release the unmanaged Resources! (Say a little more nonsense, if the programmer remembers calling Dispose (), then the Code "System.GC.SuppressFinalize (this);" You can prevent the garbage collector from calling the destructor, so that you don't have to release the unmanaged resource more than once, so we're not afraid of programmers forgetting to call the Dispose () method.

Analysis of memory management mechanism

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.