Public classcdisposable:idisposable {//destructor , which becomes protected void Finalize () after compilation, the GC will call the method before it reclaims the object~cdisposable () {Dispose (false); } //by implementing this interface, customers can explicitly dispose of objects without waiting for the GC to release resources, which is said to reduce efficiency voidIDisposable.Dispose () {Dispose (true); } //designed to release unmanaged resources into a virtual function that provides the ability to release the resources of a base class in an inheriting class protected Virtual voidreleaseunmanageresources () {//Do something ...Console.WriteLine ("Do something ..."); } //private functions to release unmanaged Resources Private voidDispose (BOOLdisposing) {releaseunmanageresources (); //True indicates that the client explicitly called the release function and informs the GC not to call the object's Finalize method//False when the GC calls the Finalize method of the object, so there is no need to tell the GC you don't call my Finalize method. if(disposing) {GC. SuppressFinalize ( This); } }
Public Static voidshowresults () {//Console.WriteLine (DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss")); intSMS =Environment.tickcount; Console.WriteLine (SMS. ToString ()); inti =0; while(I < -) { //TmpObj1 does not manually release resources, just wait for the GC to slowly release it.Cdisposable tmpObj1 =Newcdisposable (); I++; } intMMS =Environment.tickcount; Console.WriteLine (MMS-SMS); //Console.WriteLine (DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss"));i =0; while(I < -) {Console.Write (" "); //TmpObj2 calls the Dispose method, which is said to be more efficient than waiting for the GC to release it.//personally, it's because you want to see the metadata of the object individually to verify that the Dispose method is implemented .//Of course, the most important thing is that we can determine the time of release to save memory and optimize the running efficiency of the program .Cdisposable TmpObj2 =Newcdisposable (); ((IDisposable) tmpObj2). Dispose (); I++; } intEMS =Environment.tickcount; Console.WriteLine (EMS-MMS); //Console.WriteLine (DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss"));}
C # inheritance IDisposable freeing resources