. NET heap and Stack 04, garbage collection of managed and unmanaged resources, and memory allocation

Source: Internet
Author: User

In the. NET heap and Stack 01, basic concepts, value type memory allocation, the basic concepts of "heap" and "stack", and the memory allocation of value types. We know that when a method is executed, the value type instance allocates memory on the stack, and the reference type instance allocates memory on the heap, and when the method executes, the instance on the stack is automatically freed by the operating system, and the instance on the heap is reclaimed by the. NET Framework's GC.


In the. NET heap and Stack 02, value types and reference type parameter passing, and memory allocation, we learned about the memory allocations for value type parameters and reference type parameters when they are passed.


In the. NET heap and Stack 03, reference type Object copy, and memory allocation, we learned about memory allocations when copying reference type objects.

This article focuses on garbage collection, processing, and memory allocations for managed and unmanaged resources.

Mainly include:
What kind of object is considered garbage by GC?
How does GC recycle?
-GC collection of objects in the managed heap
-GC the collection and processing of objects in the unmanaged heap
※ The recovery of resources
0 Recycling by destructor
0 by implementing IDisposable interface Recycling
※ Handling of static value type variables
※ Handling of static reference type variables
When does GC recycle?
What do I do after GC is recycled?

What kind of object is considered garbage by GC?

When an object in the managed heap is not referenced by any other object, these objects become freed garbage objects waiting to be reclaimed by GC.

Each application has a set of root pointers that are not recycled and are a list maintained by the JIT compiler and the CLR runtime. Mainly include:
Global/static pointers: pointing to Global or local static variables
Stack pointer: The portion of the stack space needed to point to the application thread
Register pointer: the memory address in the portion of the CPU that is required to point to the managed heap


Above, assuming that there are 5 objects in the managed heap, 1 and 5 are referenced by pointers, 3 depends on 1, then in this set of managed heap objects, 2 and 4 are recycled and become the following:

When a new reference object is generated at run time, it is placed at the top of the set of objects in the managed heap.

How does GC recycle?

GC reclamation of objects in the managed heap

The GC uses a certain algorithm to traverse all objects in the managed heap, resulting in an unreachable object and an unreachable object that will be recycled.

GC reclamation and processing of objects in an unmanaged heap

Recycling of resources

such as files, database links, network links, and so on, how are the objects in the heap no longer managed to be recycled?


1, through the destruction function recovery

 Public class sample{    // destructor    ~Sample ()    {    }}

In the managed heap, those instances with destructors will be placed in the finalization Queue.

For those not referenced by any other object, if there is no destructor, such as 2, will be directly recycled, if there are destructors, such as 4, will be placed in the "Freachable Queue", waiting for the GC to implement the next round of recycling.


When you add destructors to a class, additional work is added to the GC at a cost that is more expensive and more realistic is to have the class implement the IDisposable interface.

2, through the realization of IDisposable interface recovery

First, let a class implement the IDisposable interface.

 Public class resourceclass:idisposable{    publicvoid  Dispose ()    {        //  TODO: Implementing recycle Logic     }}

The following implementation recycle is called in the application.

using New Resourceclass ()) {    }

Handling of static value type variables

classcounter{Private Static intS_number =0;  Public Static intGetnextnumber () {intNewnumber =S_number; //Do SOME STUFFNewnumber+=1; S_number=Newnumber; returnNewnumber; }}

As above, when the method has methods to handle the static field it is necessary to note that 2 threads simultaneously call Getnextnumber () will get the same result, and our intention is: Each call method, static field S_number increment 1.

We can lock in the processing logic block, allowing only one thread at a time to execute.

classcounter{Private Static intS_number =0;  Public Static intGetnextnumber () {Lock(typeof(Counter)) {                             intNewnumber =S_number; //Do SOME STUFFNewnumber+=1; S_number=Newnumber; returnNewnumber; }          }}

Handling of static reference type variables

 class   olympics{ public  static  collection<runner>  tryoutrunners;}  class   runner{ private  string   _filename;            private   FileStream _fstream;  public  void   GetStats () {FileInfo finfo  = new   FileInfo (_filename);          _fstream  = _filename.openread (); }}
Above, in the GetStats () method, since there is no time to close the FileStream, if Olympics happens to have 100,000 runner collection, 100,000 runner do not close FileStream the Gettats () method, It's going to be a disaster!

The singleton pattern is a good way to avoid this problem, and it guarantees that only one instance of a class exists in memory at any time.

 Public class earth{    privatestaticnew  Earth ();     Private Earth () {}      Public Static Earth getinstance () {return  _instance;}}

Above, the necessary elements of the singleton pattern include:
1. private static reference type variable
2. Private constructors
3. Get the static method of the class instance

When does GC recycle?

The GC periodically performs garbage collection, memory cleanup work, and the following scenarios start the GC:
When the managed heap is out of memory overflow
Call the Gc.collect () method to enforce garbage collection
Windows reports Low Memory
CLR Uninstall AppDomain

What do I do after GC is recycled?

GC After garbage collection, there will be "holes" in multiple objects that are collected on the managed heap, and in order to avoid the memory fragmentation of the managed heap, the memory is redistributed and the managed heap is compacted.

Resources:

C # Heap (ing) Vs Stack (ing) in. Net:part IV

You must know. NET (2nd edition), author Wang Tao.

". NET Heap and Stack "series includes:

. NET heap and Stack 01, basic concept, value type memory allocation. NET heap and Stack 02, value type and reference type parameter passing, and memory allocation. NET heap and Stack 03, reference type Object copy, and memory allocation. NET heap and Stack 04, garbage collection of managed and unmanaged resources, and memory allocation

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.