The real work of memory management in CLR is completed by the dispose () method of the idisposable interface and the class destructor. When an unmanaged resource needs to be released, the finalize () method should be executed to replace the destructor.
Idisposable is an interface that is not limited to C #. It is part of Microsoft's COM technology, it provides a general mechanism for clearing not only various types of Components in C. similar to the idisposable interface, C # applies.. NET Framework. Idisposable defines a special method, dispose (). |
If there are resources that must be released in the class, the best solution is to use the Destructor and dispose () methods at the same time.
First, let's take a look at the effect of automatic collection in CLR:
Using system; Using system. text; Class Dr { Int ci; Public DR (int I ){ This. CI = I; Console. writeline ("Dr ({0})", this. CI ); } } Class da: idisposable { Int N; Public da (int n ){ This. n = N; Dr Myr = new Dr (N ); } Public void dispose (){ Console. writeline ("dispose ({0})", this. N ); GC. suppressfinalize (this ); } ~ Da (){ Console. writeline ("~ Da ({0}) ", this. N ); } } Class demo { Public static void main (string [] ARGs ){ Da d1 = new DA (1 ); Da D2 = new DA (2 ); Da D3 = new DA (3 ); } |
We can see that the memory management system in CLR automatically removes variables in the stack order.
If I change it:
Using system; Using system. text; Class Dr { Int ci; Public DR (int I ){ This. CI = I; Console. writeline ("Dr ({0})", this. CI ); } } Class da: idisposable { Int N; Public da (int n ){ This. n = N; Dr Myr = new Dr (N ); } Public void dispose (){ Console. writeline ("dispose ({0})", this. N ); GC. suppressfinalize (this ); } ~ Da (){ Console. writeline ("~ Da ({0}) ", this. N ); } } Class demo { Public static void main (string [] ARGs ){ Da d1 = new DA (1 ); Da D2 = new DA (2 ); Da D3 = new DA (3 );
D1 = NULL; Using (D3 ){ Da D4 = new DA (4 ); } D2.dispose (); } |
Now we can see that D3 in the using block is automatically released, and it is also the first to be released. Therefore, it is advantageous to use the using block when writing a program.