C # Memory Management

Source: Internet
Author: User
  in the. NET Framework, the resources in memory (that is, the collection of all binary information) are grouped into managed resources and unmanaged resources. Managed resources must accept the management of the. NET Framework (Common language runtime), such as memory type security checks, Unmanaged resources, however, do not have to accept the CLR management .  of the. NET Framework (for more information, see Advanced programming materials for the. NET Framework or C #)   Managed resources are stored in two different places in the. NET Framework: "Stack "and" Managed heap "(hereinafter referred to as" heap "); The rule is that all value types (including references and object instances) and reference type references are stored in the stack, and the object instances represented by all references 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 characteristic of the. NET framework, not C #), but specifically, there are still some areas to be noted:   1. Value types, including references and object instances and reference-type references actually do not need a "garbage collector" to free up memory, because when they are out of scope, they automatically release the occupied memory (because they are stored in the "stack", learned the data structure that this is an advanced structure);   2. Only the object instance that the reference to the reference type points to is saved in the heap. The heap, because it is a free storage space, does not have a lifetime (the "Stack" element pops up to represent the end of the lifetime, and it means the memory is released), and it is important to note that " The garbage collector "only works on this area;"   3. " The garbage collector may not be executed immediately (when the resources in the heap need to be freed), but there is a gap between the reference of the reference type and the deletion of the object instance in the heap. Because the "garbage collector" calls are compared to consuming system resources, it is not possible to be called frequently!   (of course, user code can use method System.GC.Collect () to enforce "garbage collector")   However, in most cases, we need to explicitly release managed resources without executing the "garbage collector" ( What do we do when we need to release only a subset of the resources that are very much needed to be freed, but it's best not to call the garbage collector because the garbage collector is too wasteful of system resources, or you need to release unmanaged resources. This is the problem that we have to consider when we write code (the "garbage collector" is automatically implemented by the system, usually without user intervention), otherwise the Windows system will beTo be depleted and ...   Now, let me tell you what to do, that is, use the Dispose () method of the class to free all types of resources and use the destructor to release unmanaged Resources!   1.Dispose () methodTo release a resource through the Dispose () method, hold the "System.IDisposable" interface at the time the class is defined, and then in the class must include the method "void Dispose ()" That is defined (in the Dispose () Method is the code snippet that the user writes to release the resource, so the user will know that the Dispose () method can be used to free the resource by artificially calling it. However, it should be noted that the garbage collector does not release managed resources by invoking the Dispose () Method! 2. Destructor Method   The format for defining a destructor in C # is "~class_name ()". It is important to note that if an unmanaged resource is not used in a class, then you must not define the destructor, because the object performs the destructor, and the garbage collector The destructor is called before the managed resource is freed, and then the managed resource is actually released the second time, so that the two deletion actions are more expensive than the first time! (However, even if you have already defined a destructor in a class, there is still a way to "mask" it, which will be explained in a later code example) in the destructor, the code snippet that the user writes to release the unmanaged resource.   Use a section of code below to demonstrate how the Dispose () method and the Destructor method are used:      public class ResourceHolder:System.IDisposable     {      public void Dispose ()       {          Dispose (TRUE);          System.GC.SuppressFinalize (this);         //The preceding line of code is to prevent the "garbage collector" from invoking methods in this class          //"~resourceholder ()"         //"Why should we prevent it?" Because if the user remembers to invoke the Dispose () method, then the         //"garbage collector" has no need to "unnecessarily" release the "Unmanaged Resources" again.         //If the user does not remember the call, let the "garbage collector" help us to "superfluous" ^_^         //You can not understand what I said above, I have a more detailed explanation of the following!        }         protected virtual void Dispose (bool disposing)       {         if (disposing)           {         //This is cleaning up "managed resources" User code Snippets         }        //Here is cleanup "unmanaged resources User code Snippet      }         ~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:   MSDN, the System.Drawing.Brush.Dispose method defines this:   * * * * Release from this BRush all resources used by the 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 called the method Dispose () rather than the method Dispose (bool), however, the real way to perform the release of the work is not Dispose (), but Dispose (bool)! Why, then? Looking closely at the code, in Dispose (), the Dispose (true) is invoked, and when the argument is "true", the effect is to clean up all the managed and unmanaged resources; You must remember that I said before, "use a destructor to release unmanaged Resources", So now that Dispose () can complete the work of releasing unmanaged resources, what do you want to do with the destructor? In fact, the role of the destructor is only a "backup"!   for what?Strictly speaking, for a class that executes the interface "IDisposable", so long as the programmer uses the object instance of this class in the code, sooner or later you have to call the Dispose () method of the class, and if the class contains the use of unmanaged resources, you must also release the unmanaged Resources! Unfortunately, if the code that releases the unmanaged resources is placed in the destructor (the example above corresponds to "~resourceholder ()"), it is not possible for programmers to invoke this release code (because the destructor cannot be invoked by the user, only by the system, or by the garbage collector), So you should know why the "clean up user code snippet for 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 the event that the programmer forgets to call this method, the managed resources are certainly OK, sooner or later there will be a "garbage collector" to recycle (it will only be postponed for a while), 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 the "deconstruction method"! If you forget to call Dispose (), the garbage collector also invokes the destructor to free the unmanaged resources! (Say a little more nonsense, if the programmer remembers to call Dispose (), then Code "System.GC.SuppressFinalize" (this);   You can prevent the garbage collector from calling the destructor so that you do not have to release the unmanaged resources more than once, so we are not afraid of programmers forgetting to call the Dispose () method. So I said a lot of reasons, combined with only two points: *1. Programmers, don't forget to call Dispose () Method! (if any ^_^) *2. In case of forgetting, don't worry ... There will be!!! Because there are "garbage collector" to help us automatically invoke the destructor!

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.