. Basic use of IDisposable interfaces in net

Source: Internet
Author: User
Tags finally block

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.

One: Basic applications

1. Let's define a class that implements the IDisposable interface, with the following code:

 Public class Caryclass:idisposable
{public void dosomething () { Console.WriteLine ("Dosome thing ...."); } Public void Dispose () { Console.WriteLine (" release resources in a timely manner ");} }
2. We have two ways to invoke:
2.1. In the first way, the Dispose method is automatically called with the using statement, with the following code:
  using New Caryclass ())  {      caryclass.dosomething ();  }
2.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 execution results are the same in both ways, such as:
2.3. The advantage of using a try/finally block is that even if the code in the using is throwing an exception, the Caryclass Dispose method remains organic
The object is cleaned up. So it's better to use Try/catch from here.

II: Disposable Mode
1. In. NET because the Finalize method is called automatically when the object becomes inaccessible, we call the Dispose method of the IDisposable interface manually
Very similar to the method called by the object finalizer, we'd better put them together for processing. The first thing we think about is rewriting the Finalize method, as follows:
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 performed ...");   finally   {     base. Finalize ();   }}
2. Then we can put the call of the Dispose method together with the finalizer of the object, as follows:
 Public class caryclass:idisposable{    ~caryclass ()    {        Dispose ();    }     Public void Dispose ()    {        //cleanup resource
}
}
3. The implementation method above actually calls the Dispose method and the Finalize method, which may lead to duplication of cleanup work, so there is the following classic
Disposable mode:
 Private BOOLIsdisposed=false; Public voidDispose () {Dispose (true); Gc. Supressfinalize ( This); }protected voidDispose (BOOLdiposing) {if(! isdisposed) {if(Disposing) {//Cleanup of managed resources
}//cleanup of unmanaged Resources} isdisposed=true; } ~caryclass () {Dispose (false); }

3.1. Supressfinalize method to prevent the garbage collector from calling Object.Finalize () on objects that do not need to be terminated.
3.2. Using the IDisposable.Dispose method, the user can release the resource at any time before the object can be garbage collected. If the IDisposable.Dispose method is called, this method frees the object's resources. In this way, there is no need to terminate. IDisposable.Dispose should call the GC. SuppressFinalize so that the garbage collector does not invoke the object's finalizer.
3.3. We do not want the Dispose (bool diposing) method to be called externally, so his access level is protected . If Diposing is true, the managed and unmanaged resources are freed, and if diposing equals False The method has been called from within the finalizer by the runtime and can only release unmanaged resources.
3.4. ObjectDisposedException may be thrown if other methods are called after the object is disposed.

Three: Example analysis

1. The following code encapsulates the Dispose method, explaining how to implement a general example of Dispose (bool) in a class that uses managed and native resources:
 Public classbaseresource:idisposable {//Unmanaged Resources        PrivateINTPTR handle;//Managed Resources        PrivateComponent components;//Dispose is called        Private BOOLdisposed =false; PublicBaseResource () {} Public voidDispose () {Dispose (true); Gc. SuppressFinalize ( This); }protected Virtual voidDispose (BOOLdisposing) {if(! This. disposed) {if(disposing) {//Release managed resourcesComponents.dispose (); }//Release unmanaged resources, if disposing is false,                //Only managed resources are releasedCloseHandle (handle); handle = IntPtr.Zero;//Note this is not thread-safe} disposed =true; }//destructors are only called when we do not call the Dispose method directly        //Do not provide destructors at a time in a derived class~baseresource () {Dispose (false); }//If you have called the Dispose method after calling other methods will throw ObjectDisposedException         Public voidDoSomething () {if( This. disposed) {Throw NewObjectDisposedException (); }        }    } Public classMyresourcewrapper:baseresource {//Managed Resources        PrivateManagedresource addedmanaged;//Unmanaged Resources        PrivateNativeresource addednative;Private BOOLdisposed =false; PublicMyResourceWrapper () {}protected Override voidDispose (BOOLdisposing) {if(! This. disposed) {Try{if(disposing)                    {Addedmanaged.dispose (); } closehandle (addednative); This. disposed =true; }finally{Base.                Dispose (disposing); }            }        }    }

2. Using the CLR garbage collector, you no longer have to worry about managing the memory allocated to the managed heap, but you still need to clean up other types of resources. Managed Classes Pass
The IDisposable interface enables its consumer to release potentially important resources before the garbage collector ends the object. By following the disposable mode and leaving
An issue that requires attention, the class ensures that all of its resources are properly cleaned up, and when the cleanup code is run directly through the Dispose call or through the finalizer thread
No problems will occur.

. Basic use of IDisposable interfaces in net

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.