Basic use of the idisposable interface in. Net)

Source: Internet
Author: User

First, let's take a look at the description of this interface in msdn:

 
[Comvisible (True)]Public InterfaceIdisposable {// MethodsVoidDispose ();}
 
1. [comvisible (True)]: Indicates that the hosting type is visible to com.

2. The main purpose of this interface is to release unmanaged resources. When a hosted object is no longer used, the garbage collector Automatically releases the memory allocated to the object. However, the time for garbage collection cannot be predicted. In addition, the garbage collector knows nothing about window handles, opened files, streams, and other unmanaged resources. Use the dispose method of this interface with the garbage collector to explicitly release unmanaged resources. When an object is no longer needed, the user of the object can call this method.

I. Basic Applications

1. Let's define a class that implements the idisposable interface,CodeAs follows:

 Public ClassCaryclass: idisposable
{Public VoidDosomething () {console. writeline ("Do some thing ....");}Public VoidDispose () {console. writeline ("Release resources in time");}}
 
2. We have two ways to call:
. The first method is to use the using statement to automatically call the dispose method. The Code is as follows:
 
Using(Caryclass =NewCaryclass () {caryclass. dosomething ();}
 
2.2 Method 2: Call the dispose method of this interface. The Code is as follows:
Caryclass =NewCaryclass ();Try{Caryclass. dosomething ();}Finally{Idisposable disposable = caryclassAsIdisposable;If(Disposable! =Null) Disposable. Dispose ();}
 
The execution results of the two methods are the same, for example:
 
 
 
. The advantage of using try/finally blocks over using blocks is that even if the using code causes an exception, the dispose method of caryclass still has an organic
The object is cleared. Therefore, try/catch is better.
 

Ii. Disposable Mode
 
1. In. net, because the Finalize method is automatically called when the object becomes inaccessible, we manually call the dispose method of the idisposable interface.
The method called by the object Terminator is very similar. We 'd better put them together for processing. The first thing we think of is to override the Finalize method, as shown below:
Protected Override VoidFinalize () {console. writleline ("Destructor execution...");}
 
When we compile this code, we find that the compiler reports the following error:
 
 
 
This is because the compiler completely shields the Finalize method of the parent class. The Compiler prompts us to provide an destructor if we want to override the Finalize method.
Instead, we provide an destructor as follows:
 
~ Caryclass () {console. writeline ("Destructor execution...");}
 
In fact, the Destructor compiler will convert it into the following code:
 
Protected Override VoidFinalize (){Try{Console. writleline ("Destructor execution...");}Finally{Base. Finalize ();}}
2. Then we can put the call of the dispose method together with the object Terminator for processing, as shown below:
 
Public ClassCaryclass: idisposable {~ Caryclass () {dispose ();}Public VoidDispose (){// Clear Resources
}
}
 
3. The above implementation method actually calls the dispose method and finalize method, which may lead to repeated cleaning work, so the following classic
Disposable mode:
  private   bool  isdisposed =  false ;  Public   void  dispose () {dispose ( true ); GC. supressfinalize ( This );}  protected   void  dispose ( bool  diposing) { If  (! Isdisposed) { If  (disposing) { // clear managed resources 
}< span style =" color: #008000 "> // clear unmanaged resources } isdisposed = true ;}~ Caryclass () {dispose ( false ) ;}

3.1. supressfinalize method to prevent the garbage collector from calling object. Finalize () for objects that do not need to be terminated ().
3.2. Using the idisposable. dispose method, you can release resources at any time before you can recycle objects as garbage. If the idisposable. dispose method is called, this method releases the resource of the object. In this way, there is no need to terminate. Idisposable. Dispose should call GC. suppressfinalize so that the garbage collector does not call the object Terminator.
3. We do not want dispose (BoolThe method is called externally, so its access level isProtected. If the value of diposing is true, the managed and unmanaged resources are released. If the value of diposing is false, the method has been called by the runtime from the Terminator and can only be released.
. If other methods are called after an object is released, objectdisposedexception may be triggered.

Iii. instance resolution

 
1. The following Code encapsulates the dispose method and describes how to implement a general example of dispose (bool) in classes that use hosted and local resources:
 Public   Class Baseresource: idisposable { // Unmanaged Resources  Private Intptr handle;// Host resources  Private Component components; // Whether dispose is called  Private   Bool Disposed = False ; Public Baseresource (){} Public   Void Dispose () {dispose ( True ); GC. suppressfinalize ( This );} Protected   Virtual   Void Dispose ( Bool Disposing ){ If (! This . Disposed ){ If (Disposing ){ // Release managed resources Components. Dispose ();} // Release unmanaged resources. If disposing is false,  // Only managed resources are released Closehandle (handle); handle = intptr. zero; // Note that this is not thread-safe } Disposed = True ;} // The Destructor is called only when the dispose method is not directly called.  // You do not need to provide the destructor in the derived class. ~ Baseresource () {dispose (False );} // If you have already called the dispose method, objectdisposedexception will be thrown when you call other methods.  Public   Void Dosomething (){ If ( This . Disposed ){ Throw   New Objectdisposedexception ();}}} Public   Class Myresourcewrapper: baseresource { // Host resources  Private Managedresource addedmanaged; // Unmanaged Resources Private Nativeresource addednative; Private   Bool Disposed = False ; Public Myresourcewrapper (){} Protected   Override   Void Dispose ( Bool Disposing ){ If (! This . Disposed ){ Try { If (Disposing) {addedmanaged. Dispose ();} closehandle (addednative ); This . Disposed = True ;} Finally { Base . Dispose (disposing );}}}}

2. Using the CLR garbage collector, you do not have to worry about how to manage the memory allocated to the managed heap, but you still need to clear other types of resources. Managed classes pass
The idisposable interface enables the user to release potentially important resources before the spam collector terminates the object. By following the disposable mode and leaving
The class can ensure that all its resources are correctly cleared, and when the code is directly called through dispose or run through the terminator thread
No problem occurs.

 

 

AboveArticleFrom http://www.cnblogs.com/carysun/archive/2008/06/15/dispose.html

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.