Recommendation 69: You should use finally to avoid resource leaks
Unless an exception occurs that causes the application to break, finally will always be executed before return. Finally, this language feature determines that the best place to release resources is in the finally block, and that resource deallocation executes from bottom to top as the call stack. The following code verifies this by first defining a class that needs to be freed:
classclassshoulddisposebase:idisposable {string_methodname; PublicClassshoulddisposebase (stringmethodName) {_methodname=MethodName; } Public voidDispose () { This. Dispose (true); Gc. SuppressFinalize ( This); Console.WriteLine ("in the method:"+ _methodname +"be released! "); } protected Virtual voidDispose (BOOLdisposing) { if(disposing) {//perform basic cleanup code } } ~classshoulddisposebase () { This. Dispose (false); } }
Again to simulate a call stack:
Static voidMain (string[] args) {Method1 (); } Static voidMethod1 () {classshoulddisposebase C=NULL; Try{C=NewClassshoulddisposebase ("Method1"); METHOD2 (); } finally{c.dispose (); } } Static voidMethod2 () {classshoulddisposebase C=NULL; Try{C=NewClassshoulddisposebase ("Method2"); } finally{c.dispose (); } }
Output:
In method: Method2 is released!
In method: Method1 is released!
Finally does not terminate because of an exception that exists in the call stack, and the CLR executes the catch block before executing the finally block. As follows:
Static voidMain (string[] args) {Method3 (); } Static voidMethod3 () {classshoulddisposebase C=NULL; Try{C=NewClassshoulddisposebase ("Method3"); METHOD4 (); } Catch{Console.WriteLine ("an exception was caught in the Method3. "); } finally{c.dispose (); } } Static voidMethod4 () {classshoulddisposebase C=NULL; Try{C=NewClassshoulddisposebase ("METHOD4"); Throw NewException (); } Catch{Console.WriteLine ("an exception was caught in the Method4. "); Throw; } finally{c.dispose (); } }
Output:
An exception was caught in the Method4.
In method: METHOD4 is released!
An exception was caught in the Method3.
In method: Method3 is released!
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
157 recommendations for writing high-quality code to improve C # programs-Recommendation 69: Use finally to avoid resource leaks