C # implement the idispose Mode

Source: Internet
Author: User

The gc mechanism of. Net has two problems: GC cannot release all resources, and it cannot release unmanaged resources. Second, GC is not real-time, and there is uncertainty in All GC.
To solve this problem,. NET provides destructor

Public class disposeclass: system. idisposable {// The Public void dispose () method explicitly called by the programmer {// call the parameter-based dispose method to release the managed and unmanaged resource dispose (true ); // If you manually call dispose to release resources, the Destructor is unnecessary. In this case, GC is prevented from calling the destructor system. GC. suppressfinalize (this);} // The dispose method of protected to ensure that it is not called externally. // Pass in the bool value disposing to determine whether to release the Managed Resource Protected void dispose (bool disposing) {If (disposing) {// todo: add the code for clearing "managed resources" here, which should be xxx. dispose () ;}/// todo: add the code for clearing "unmanaged resources" Here} // destructor for GC calls ~ Disposeclass () {dispose (false); // release unmanaged resources }}

Even if we forget to call dispose when appropriate, GC will help us clean up unmanaged resources when releasing objects. The role played by GC is only a means of protection. It should act as such a role, and we cannot rely too much on it. In fact, when a large module exits, we should also manually call GC. Collect in time for garbage collection.

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.