157 recommendations for writing high-quality code to improve C # programs--suggest that the 48:dispose method should allow multiple calls

Source: Internet
Author: User

It is recommended that the 48:dispose method be allowed to be called multiple times

A type of Dispose method should be allowed to be called multiple times without throwing an exception. In view of this, the type internally maintains a private bool variable disposed, as follows:

Private BOOL false;

In the actual method of cleaning the code, add a judgment:

if (disposed) {      return;       } // omit the code for the Cleanup section and assign a value of disposed to true at the end of the method true;

This means that if the type has been cleaned up, the cleanup will no longer work.

object is called by the Dispose method and does not indicate that the object is set to NULL, and that the garbage collection mechanism reclaims the memory and has been completely stored. In fact, the reference to the object may still be in. However, if the object is dispose of, the normal state of the object is no longer present, and if the object's public method is called, a objectdisposedexception should be thrown. Method Samplepublicmethod demonstrates this method for us:

         Public void Samplepublicmethod ()        {            if  (disposed)            {                thrownew objectdisposedexception ( " SampleClass " " SampleClass is disposed " );            }             // omitted        }

Therefore, in Dispose mode, you should always create a variable for the type that indicates whether the object has been dispose of.

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--suggest that the 48:dispose method should allow multiple calls

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.