Recovery of. NET Unmanaged Resources

Source: Internet
Author: User

There are two ways of releasing unmanaged resources

1. destructor

2. Implement System.IDisposable interface

First, the destructor

The constructor can specify certain actions that must be made when an instance of the class is created, or a destructor can be called when the object is deleted by the garbage collector. At first, destructors appear to be the best place to put code that frees unmanaged resources and performs general cleanup operations. But things are not so simple. Because the garbage collector's running rules determine that code that needs to run at some point cannot be placed in the destructor, if the object consumes valuable and important resources, it should be released as soon as possible, and you cannot wait for the garbage collector to release it.

Instance

C # codeCopy
Using System;
Using System.Collections.Generic;
Using System.Linq;
Namespace Memrelease
{    class program    {        ~program ()        {            //Orders.        }         static void Main (string[] args)        {        }      

In Il dasm, you will find that there is no method for this destructor. When compiling a destructor, the C # compiler implicitly compiles the code of the destructor into the corresponding code of the Finalize () method, ensuring that the Finalize () method of the parent class is executed to see the compiler for the destructor in this code:

C # codeCopy
        Finalize () CIL managed
{  //Code size       (0xe)  . maxstack  1  . Try  {    il_0000:  nop    il_0001:  NOP    il_0002:  leave.s    il_000c  }  //end. Try  finally  {    il_0004:  ldarg.0    il_0005:  call       instance void [Mscorlib]system.object::finalize ()    il_000a:  NOP    il_000b:  endfinally  }  //End handler  il_000c:  nop  il_000d:   

There are several issues with using destructors to release resources :

1, compared with C + + destructor, the problem of C # destructor is their uncertainty. When you delete a C + + object, its destructor executes immediately, but because of how the garbage collector works, it is not possible to determine when the destructor for a C # object executes.

2. The execution of the C # destructor delays the time at which the object will eventually be removed from memory. Objects with destructors require 2 processing to be deleted: the first time the destructor is called, no object is deleted, and the second call actually deletes the object.

Second, IDisposable interface

The IDisposable interface defines a pattern that provides a deterministic mechanism for releasing unmanaged resources and avoids the problems inherent in the destructor that are related to garbage functions. The IDisposable interface declares a method of Dispose (), which returns void without parameters.

1. MSDN recommends implementing the IDisposable interface in the following mode

C # codeCopy
public class Foo:idisposable
{Public     void Dispose ()     {        Dispose (true);        Gc. SuppressFinalize (this);     }       protected virtual void Dispose (bool disposing)     {        if (!m_disposed)        {            if (disposing)            {               //release managed resources            }              //release unmanaged Resources              m_disposed = true;        }     }       ~foo ()     {Dispose (false);} private bool m_disposed;}    

In the . NET, there are actually two functions for freeing resources:Dispose and Finalize

(1),finalize is intended to release unmanaged resources, and Dispose is used to release all resources, including managed and unmanaged

(2),void Dispose (bool disposing) function uses a disposing parameter to distinguish whether the current is a Dispose () call

If it is called by Dispose (), both managed and unmanaged resources need to be released at the same time. If it is called by ~foo () (That is , the Finalize () of C #) , then only the unmanaged resources need to be freed.

(3),the Dispose () function is explicitly called by other code and requires the release of resources, and finalize is called by the GC

InWhen the GC is calledfoo may not need to be destroyed, And even if it is to be destroyed, it will be called by GC. So in finalize only need to release the unmanaged resources. On the other hand, because in dispose () Managed and unmanaged resources have been released, so the object is dispose () calls GC. SuppressFinalize (this) avoids repeated calls to

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.

Finalize,dispose guarantees the

(1), Finalize releases only unmanaged resources;

(2), Dispose releases both managed and unmanaged resources;

(3), repeated calls to finalize and dispose are no problem;

(4), Finalize, and dispose share the same resource-release policies, so there is no conflict between them.

2. IDisposable example

 C # code replication
Namespace Resource Recycling
{Class Program{static void Main (string[] args){//use using to implement IDisposable classes for resource management/* When you get an object, first determine whether the object implements the IDisposable interface, if implemented, it is best to use a using to wrap the object, to ensure that the object is released after use, otherwise there is likely to be a resource leakage problem */using (Telphone t 1 = new Telphone ()){T1.                Open (); T1.                Speak ("Hello"); T1.                Bomb (); T1. Dispose ();//If the Dispose () method is called here to free resources, then execute t1. The Open () method is wrong, the telephone line has been cut off, can no longer call the T1.                Open (); T1.            Speak ("I am back!");        Once the}//code executes here, it calls the Dispose method for resource reclamation Console.readkey (); }    }<summary>///Telphone class implements IDisposable interface///</summary> class Telphone:idisposable{<summary>///Telephone status///</summary> private telphonestate State;<summary>///Telephone//</summary> public void Open (){if (state = = telphonestate.disposed){throw new Exception ("The phone line has been cut off and cannot be opened! "); } state = Telphonestate.open; Console.WriteLine ("Pick Up the phone"); }//<summary>/////<param Name= "s" > Talking content </param> public void Speak (string s) {if (state! = Telphonestate.open) {throw new Exception ("no Connection");} Console.WriteLine (s); } ///<summary>///Hang up phone///</summary> public void Bomb () {state = Telphonestate.close; Console.WriteLine ("Hang Up the phone"); } IDisposable Member}///<summary>///  Telephone Status enumeration///</summary> enum telphonestate {Open, Close, Dispo SED}}       

program run result :

Iii. examples of destructors and IDisposable mixed calls

 C # code replication
public class Resourceholder:idisposable
{      private bool Isdispose = false;            Displays the Dispose method called public void Dispose ()       {           Dispose (true);          Gc. SuppressFinalize (this);        }       The actual purge method protected virtual void Dispose (bool disposing)       {            if (!isdisposed)           {       if ( disposing)         {                       //Here the operation to clear the managed object is performed.                  }                  This performs an operation to clear the unmanaged object            }        isdisposed=true;      }      destructor       ~resourceholder ()      {Dispose (false);}}      

Recovery of. NET Unmanaged Resources

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.