The previous section gives you an introduction to the operating mechanism of the. Net GC, and the following are important methods related to GC.
Section II. GC Key Method Analysis
1.Dispose () method
Dispose can be used to release all resources, both managed and unmanaged, and needs to be implemented by itself.
Most unmanaged resources require manual release, we should expose a method for releasing unmanaged resources, there are many ways to release unmanaged resources, the Dispose method that implements the IDispose interface is the best, which can give the programmer with your class library a clear explanation, Let them know how to release your resources, and the using statement used in C # is fast and automatically calls the Dispose method when you leave the statement block.
It is important to note that if the base class implements the IDispose interface, its derived class must also implement its own idispose and call the Dispose method in the base class in its Dispose method. This is the only way to ensure that when you use a derived class instance, you release the resource, along with the unmanaged resources in the base class.
Episode: The difference between using use and try+finally
It can be said that 2 does not make any difference, because using is just editor-level optimization, it has the same effect as try+finally, the following is a section of code that uses using, which is also presented in the IL phase as try+finally:
C#:
public partial class _default:system.web.ui.page
{
protected void Page_Load (object sender, Eve Ntargs e)
{
using (DataSet ds = new DataSet ())
{
}
}
MSIL:
. Method family Hidebysig instance void Page_Load (Object sender,class [Mscorlib]system.eventargs e) CIL Managed
{
//code size (0x1d)
. Maxstack 2
. Locals init ([0] class [System.data]system. Data.dataset ds,
[1] bool cs$4$0000)
Il_0000:nop
Il_0001:newobj instance void [Sy Stem. Data]system.data.dataset::.ctor ()
il_0006:stloc.0
. Try
{
Il_0007:nop
il_00 08:nop
il_0009:leave.s il_001b
}//end. Try
finally
{
Il_000b:ldloc .0
Il_000c:ldnull
il_000d:ceq
il_000f:stloc.1
il_0010:ldloc.1
IL _0011:brtrue.sil_001a
il_0013:ldloc.0
Il_0014:callvirt instance void [mscorlib]system.idisposable::D ispose () il_0019:nop
Il_001a:endfinally
}//End handler
Il_001b:nop
Il_001c:re T
}/End of method _default::P age_load
However, the advantage of using is that when the code leaves a using block, the using automatically invokes the Dispose () method of the IDispose interface.