Dispose and Finalizer in C #

Source: Internet
Author: User

the CLR provides automatic memory management. Managed Memory does not need to be explicitly released. When the garbage Collection is performed , it is automatically released.

However, managed memory is only one of many kinds of system resources. In addition to the managed memory, other resources that need to be explicitly freed are known as the unmanaged resource, such as open file descriptors, open database connections, and so on.

CLR provides a mechanism for releasing unmanaged Resources . A virtual method Finalize is declared in System.Object, which resembles a destructor in C + + when an Object When the memory is reclaimed, theGC calls the Finalize method to release unmanaged Resources. the type that overrides the Finalizer is also called the finalizable type.

 Public classcomplexresourceholder:idisposable {PrivateINTPTR buffer;//Unmanaged Memory Buffer    PrivateSafeHandle resource;//disposable handle to a resource             PublicComplexresourceholder () { This. Buffer = ...//allocates memory         This. Resource = ...//allocates the resource    }    ~Complexresourceholder () {releasebuffer (buffer);//Release unmanaged Memory    }}

But there's a bad place to use finalizer.

    The call time for
    1. finalizerfinalizergcframework call. This is unacceptable for some scarce system resources.
    2. gc< Span lang= "ZH-CN" > When you are ready to reclaim memory for an object, if the object requires finalizefinalize queue, then another thread pulls the object from the queue and calls finalizer gc

.net frameworksystem.idisposable interface, by implementing the Dispose method of the interface, we You can call this method manually, so you can control unmanaged resources release time. frameworkgc. Suppressfinalize method tells gc The object has been manually Disposedfinalized

. NET recommended IDisposable interface implementation is as follows

     Public classcomplexresourceholder:idisposable {PrivateINTPTR buffer;//Unmanaged Memory Buffer        PrivateSafeHandle resource;//disposable handle to a resource                     PublicComplexresourceholder () { This. Buffer = ...//allocates memory             This. Resource = ...//allocates the resource        }                //Implement IDisposable. //Does not make the this method virtual. //A derived class should not is able to override the This method.         Public voidDispose () {Dispose (true); //This object is cleaned up by the Dispose method. //Therefore, you should the call GC. Supressfinalize to//Take this object off the finalization queue//and prevent finalization code for this object//From executing a second time.Gc. SuppressFinalize ( This); }                //Use C # destructor syntax for finalization code. //This destructor would run only if the Dispose method//does not get called. //It gives your base class the opportunity to finalize. //provide destructors in types derived from the This class.~Complexresourceholder () {Dispose (false); }            //Dispose (bool disposing) executes in and distinct scenarios. //If disposing equals True, the method has been called directly//or indirectly by a user ' s code. Managed and unmanaged Resources//can be disposed. //If disposing equals false, the method has been called by the//runtime from inside the finalizer and your should not reference//Other objects. Only unmanaged resources can be disposed.        protected Virtual voidDispose (BOOLdisposing) {                                //Release unmanaged Memoryreleasebuffer (buffer); //Release other disposable objects            if(disposing) {if(resource!=NULL) resource.            Dispose (); }        }        }

Reference:

1. Http://msdn.microsoft.com/zh-cn/library/system.idisposable.dispose (v=vs.110). aspx

2. http://msdn.microsoft.com/en-us/library/b1yfkh5e (v=vs.110). aspx

Dispose and Finalizer in C #

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.