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: