Using System;
Using System. Collections. Generic;
Using System. Text;
Namespace finalize
{
Class Program
{
Static void Main (string [] args)
{
MyResource myone = new MyResource ();
Try
{
// Do something
}
Finally
{
Myone. Dispose ();
Myone. Close (); // The action is not executed because it has been released.
Myone. Close ();
}
Using (MyResource mytwo = new MyResource ())
{
// Do something
}
Console. Read ();
}
}
Public class MyResource: IDisposable
{
Private bool IsDisposed; // determines whether the class is released.
Public void Dispose ()
{
Dispose (true); // call Dispose (true) to release the Dispose method of the object referenced by this class and the unmanaged resources used by the class itself;
}
Public void Close ()
{
Dispose (true );
}
Public void Dispose (bool disposing)
{
If (! This. IsDisposed)
{
If (disposing)
Console. WriteLine ("Release the Dispose method of the object referenced by this class ");
Console. WriteLine ("Release the unmanaged resources used by the class itself ");
This. IsDisposed = true;
If (disposing)
GC. SuppressFinalize (this); // block the terminator call
}
}
~ MyResource ()
{
Dispose (false); // destructor call Dispose (false) to release unmanaged resources );
}
}
}