. Basic usage of IDisposable interface in net

Source: Internet
Author: User

First look at the MSDN instructions on this interface:

[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 in use, the garbage collector automatically releases the memory allocated to that object. However, the time for garbage collection cannot be predicted. In addition, the garbage collector knows nothing about unmanaged resources such as window handles or open files and streams. Use the Dispose method of this interface with the garbage collector to explicitly dispose of unmanaged resources. When an object is no longer needed, the object's consumer can call this method.

One: Basic application

1. We define a class that implements the IDisposable interface, and the code is as follows:

public class caryclass:idisposable
{public
void dosomething ()
{
Console.WriteLine () {Some thin  G. ... ");
Public
void Dispose ()
{
Console.WriteLine ("Timely release of resources");
}
}

2. We have two ways to invoke:

2.1. In the first approach, the Dispose method is automatically invoked using the USE statement, as follows:

using (Caryclass Caryclass = new Caryclass ())
{
caryclass.dosomething ();
}

2.2 The second way, reality calls the Dispose method of the interface, the code is as follows:

Caryclass Caryclass = new Caryclass ();
Try
{
caryclass.dosomething (); 
}
Finally
{
IDisposable disposable = Caryclass as IDisposable;
if (disposable!= null) disposable.  Dispose ();
}

The results of the two methods are the same, as shown in the following figure:

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.