157 recommendations for writing high-quality code to improve C # programs-Recommendation 69: Use finally to avoid resource leaks

Source: Internet
Author: User
Tags finally block

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.