. NET resource releases (managed and unmanaged resources)

Source: Internet
Author: User

1. Managed Resources

such as int, float, datetime, etc. are managed resources; NET 80% of resources are managed resources;

The collection of managed resources automatically frees the memory allocated to the object through the GC (garbage collector), but it cannot predict when the garbage collection will take place, and we cannot control when the system recycles the resources.

2. Unmanaged Resources

Like Applicationcontext,brush,component,componentdesigner,container,context,cursor,filestream,font,icon,image, Matrix,object,odbcdatareader,oledbdatareader,pen,

Resources, such as Regex,socket,streamwriter,timer,tooltip, are unmanaged resources.

The garbage collector knows nothing about unmanaged resources and cannot automatically reclaim unmanaged resources; We must display the release of unmanaged resources. When an object is no longer needed, the consumer of the object can call this method.

—————————————————————————————————— Split Line ———————————————————————————————————————————————

How unmanaged resources are released, the. NET Framework provides a object.finalize method that allows an object to properly clean up its unmanaged resources when the garbage collector reclaims the memory used by the object.

Unmanaged resources are reclaimed by the Object.Finalize method, and you must override the Finalize method in the class if you want the garbage collector to perform cleanup operations on the object before it reclaims the object's memory . However, you can see that in real programming you cannot override the method Finalize (), and in C #, you can automatically generate a Finalize method and a call to the base class's Finalize method through a destructor.

protected Override void Finalize () {     console.writleline (" destructor execution ... " );}

When we compile this code, we find that the compiler will report the following error:

This is because the compiler completely blocks the Finalize method of the parent class, and the compiler prompts us to override the Finalize method to provide a destructor to
Instead, let's provide a destructor:

~Caryclass ()  {      Console.WriteLine (" destructor execution ... " );  }

In fact, the destructor compiler transforms it into the following code:

protected Override void Finalize () {   try   {     console.writleline (" destructor execution ... " );   }    finally    {     base. Finalize ();   }}

In programming, the override Method Finalize () is not recommended because implementing a Finalize method or destructor can have a negative impact on performance. A simple reason for this is that the memory used to reclaim objects using the Finalize method requires at least two garbage collection, and when the garbage collector reclaims it, it reclaims only inaccessible memory without the finalizer (Finalize method), and he cannot recycle a finalizer (Finalize method) Of memory that cannot be accessed

Second recommended alternative destructors is to use the System.IDisposable interface

Let's start with the description of this interface on MSDN:

[ComVisible (true)]  Public Interface idisposable{    //  Methods    void  Dispose ();}

1.[comvisible (True)]: Indicates that the managed type is visible to COM.

2. The primary purpose of this interface is to release unmanaged resources. When a managed object is no longer being used, the garbage collector automatically frees the memory allocated to the object. However, it is not possible to predict when garbage collection will take place. In addition, the garbage collector is ignorant of unmanaged resources such as window handles or open files and streams. Use the Dispose method of this interface with the garbage collector to explicitly release unmanaged resources. When an object is no longer needed, the consumer of the object can call this method.

Basic applications:

 Public class caryclass:idisposable {    publicvoid  dosomething ()    {       Console.WriteLine (  "dosome thing .... " );    }      Public void Dispose ()    {       Console.WriteLine (" release resources in a timely manner ");}    }

We call it in two different ways

1.1. In the first way, the Dispose method is automatically called with the using statement, with the following code:

using New Caryclass ()) {     caryclass.dosomething ();  }

1.2 The second way, the actual call to the interface of the Dispose method, the code is as follows:

New Caryclass (); Try {     caryclass.dosomething ();} finally {     as  IDisposable;      if NULL )         Disposable. Dispose (); }    

The result of the execution of the two methods is the same:

3. Classic Application Disposable Mode

Private BOOLIsdisposed=false;  Public voidDispose () {Dispose (true); Gc. Supressfinalize ( This); }   protected voidDispose (BOOLdiposing) {       if(!isdisposed) {           if(Disposing) {//clean up Managed resources         }           //Cleanup of unmanaged Resources} isdisposed=true; }   ~Caryclass () {Dispose (false); } 

In this pattern, the void Dispose (bool disposing) function distinguishes between the current Dispose () call or the destructor call by a disposing parameter ( when disposing is "true", the description of the Dispose () is called by the program and requires the release of managed and unmanaged resources, and when disposing is "false", it is stated that Dispose () is called by the destructor (that is, the Finalize ()) of C #, only to release the unmanaged resources).

This is because the Dispose () function is explicitly called by other code in the program and requires that the resource be freed, and finalize is called by the GC. Other managed objects referenced by MyResource may not need to be destroyed when the GC is called, and will be called by the GC even if it is to be destroyed. So only unmanaged resources can be released in finalize. On the other hand, because managed and unmanaged resources have been freed in Dispose (), it is not necessary to call finalize again when the object is reclaimed by GC, so call Gc.suppressfinalize (this) in Dispose () Avoid repeating the call to finalize.

However, even if finalize and dispose are repeatedly called, there is no problem, because the existence of variable m_disposed, the resources will only be freed once, the redundant calls will be ignored.

As a result, the above pattern guarantees:
1. Finalize releases only unmanaged resources;
2. Dispose releases both managed and unmanaged resources;
3. It is no problem to call finalize and dispose repeatedly;
4. Finalize and Dispose share the same resource release policy, so there is no conflict between them.

. NET resource releases (managed and unmanaged resources)

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.