Use of the. NET recycle mechanism

Source: Internet
Author: User
A terminated object that is permanently memory heavy and unused will consume a lot of system resources. The. NET garbage collector puts it in the abort queue, and once the time is ripe, the object wakes up and invokes his finalize method to completely terminate him, but using this mechanism, you can put a resource-intensive class into an object pool and use it repeatedly throughout the lifetime of the program (the end sign is CL R does not believe that any of the application's roots exist in the process. We call these mega-classes expensive objects, and here's a discussion of the structure of the object pool that manages the expensive object.

Class expensive{

Static Stack pool = new stack ();

public static expensive Getobjectfrompool () {

Retun (expensive) pool. Pop ();

}

public static void Shutdownthepool () {

Pool = null;

}

Public expensive () {

To construct an object first

Pool.push (this);

}

Finalize () {

If (pool!=null) {

Gc. Registerforfinally (this;)//wake him up and kill him first

Pool.push (this); To add a "sober" object to the object pool and bring him back to life.

}

}

}

Class app{

Static void Main () {

New expensive ();

......

Expensive E = Expensiv. Getobjectfrompool ();

Now you can use E.

Expensive.shutdownthepool ()//Close the object pool before shutting down the application, otherwise it will leave a "hole" in memory because finalize has been rewritten

}

}



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.