157 recommendations for writing high-quality code to improve C # programs--recommendation 46: Explicitly releasing resources requires an inherited interface IDisposable

Source: Internet
Author: User

Recommendation 46: Explicitly releasing resources requires an inherited interface IDisposable

Each of the types in C # represents a resource, and resources fall into two categories:

Managed Resources : the resources that are allocated and freed by the CLR, that is, objects from the CLR that are new.

unmanaged Resources : Objects that are not managed by the CLR, such as Windows kernel objects, or files, database connections, sockets, Coom objects, and so on.

If our type uses unmanaged resources, or if we need to release the managed resources in a display, then we need to have the type inherit the interface IDisposable, without exception. This is equivalent to telling the caller that the type resource is required to display the release resource, and you need to call the type of Dispose method.

A standard type that inherits the IDisposable interface should be implemented as follows, which we call the Dispose pattern:

     Public classsampleclass:idisposable {//Demo Creating an unmanaged resource        PrivateIntPtr Nativeresource = Marshal.allochglobal ( -); //Demo Creating a managed resource        PrivateAnotherresource Managedresource =NewAnotherresource (); Private BOOLdisposed =false; /// <summary>        ///implementing the Dispose method in IDisposable/// </summary>         Public voidDispose () {//must be TrueDispose (true); //notifies the garbage collection mechanism not to call finalizers (destructors)Gc. SuppressFinalize ( This); }        /// <summary>        ///is not necessary, providing a close method is just for more compliance with other languages (such as///Specification for C + +)/// </summary>         Public voidClose () {Dispose (); }        /// <summary>        ///must prevent programmers from forgetting to explicitly call the Dispose method/// </summary>~SampleClass () {//must be falseDispose (false); }        /// <summary>        ///protected virtual for non-sealed class modification///Seal class decoration with private/// </summary>        /// <param name= "disposing" ></param>        protected Virtual voidDispose (BOOLdisposing) {            if(disposed) {return; }            if(disposing) {//clean up Managed resources                if(Managedresource! =NULL) {managedresource.dispose (); Managedresource=NULL; }            }            //Cleanup of unmanaged Resources            if(Nativeresource! =IntPtr.Zero) {Marshal.freehglobal (Nativeresource); Nativeresource=IntPtr.Zero; }            //let the type know that they have been releaseddisposed =true; }         Public voidSamplepublicmethod () {if(disposed) {Throw NewObjectDisposedException ("SampleClass","SampleClass is disposed"); }            //omitted        }    }    classanotherresource:idisposable { Public voidDispose () {}}

Inheriting the IDisposable interface also facilitates the implementation of syntactic sugar using. Such as:

using New SampleClass ()) {    // omit }

Equivalent to:

SampleClass cl; Try {    new  SampleClass ();     // omitted }finally{    cl. Dispose ();}

If there are two types of consistent objects, the using can also be used:

using New SampleClass (), c2=new  SampleClass ()) {  // omitted }

If the two types are inconsistent, you can use this:

using New SampleClass ()) using New Sampleanotherclass ()) {    // omit }

Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia

157 recommendations for writing high-quality code to improve C # programs--recommendation 46: Explicitly releasing resources requires an inherited interface IDisposable

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.