. NET object creation, garbage collection, and manual processing of unmanaged resources

Source: Internet
Author: User

This article is used to comb the creation of objects, garbage collection, and the manual processing of unmanaged resources.


→ First run the application and create a Windows process.

→CLR creates a contiguous virtual address space, which is the managed heap. Moreover, the address space initially does not have a corresponding physical storage space.

The virtual address space is divided into 2 segments. A segment is a normal heap, also called a GC heap, where an instance of a reference type object of size less than 85000 bytes is assigned here, and the other is a large object heap, where an instance of a reference type object with a size greater than or equal to 85000 bytes is allocated here.

For client applications, the size of each segment is roughly 16MB, and for a server-side application, the size of each segment is roughly 64MB. In addition, the size of each segment varies depending on the number of CPUs, whether it is a 32-bit or 64-bit operating system.

As each section is filled with objects, the CLR allocates more extents until the entire process space is full, and each process can use 4GB of memory.

A pointer nextobjptr is maintained on the managed heap, pointing to where the next object is allocated on the managed heap.

The managed heap is divided into garbage-collected heap gc heap and load heap loader heap According to the different storage information. Garbage collection Heap GC Heap storage object instance, managed by GC, load heap Loader heap stores metadata information in the AppDomain, such as base type, static field, static method, interface information, etc., not managed by GC, Its life cycle begins with the creation of the AppDomain and ends with the uninstall AppDomain. At this point, the managed heap and other aspects are roughly distributed like this:

→ create an object on the managed heap

-Reference type Object creation

Use the new keyword to create a reference type object.

FileStream fs = new FileStream (@ "", FileMode.Open);

The above code is compiled by the compiler and is actually a newobj instruction in the generated intermediate IL code. Il-related directives also include: The LDSTR directive is used to create a string type object, Newarr is used to assign a new array object, and the box instruction is used to copy the value Type field onto the managed heap when the value type is converted to a reference type.

Use the following code to understand the approximate process of creating objects on the managed heap:

 Public class Employee
{
    Private int _id;
    Private Status _status;
     Public Employee ()
    {
        _id = 1;
        New Status ();
    }
}
 Public class Sales:employee
{
     Public bool _islive;
     Public BOOL Islive ()
    {
        return _islive;
    }
     Public Static void Main ()
    {
        Sales _sales;
        New Sales ();
        true;
        Console.WriteLine (_sales. Islive ());
    }
}
 Public class Status
{
    Private int _years;
    Private char _level = "A";
}

1. Execute sales _sales, which opens up 4byte of memory space on the thread stack to hold the managed heap address of the sales object, which is null at this time.


2. _sales = new Sales (), recursively calculates the total number of bytes of the sales instance object, starting with the sales itself, to the parent class employee, until the base class System.Object, the specific byte calculation process is as follows:

Sales object Instance bytes = Number of bytes in field _islive is 1byte
The number of additional members Typehandler bytes of the Sales object instance =4byte
The number of additional members Syncblockindex bytes of the Sales object instance =4byte
The parent of the Sales object instance Employee bytes = Number of bytes in field _id 4byte + field _status save a reference to the Status object instance as 4byte

1+4+4+4+4=17byte, take into account that the memory block is always in accordance with 4byte memory alignment, so the completion to 20byte.

Because a status class is instantiated in the constructor of the parent employee of sales, you also need to calculate the number of bytes for the Status object instance:
Status Object Instance bytes = Number of bytes in field _years 4byte + bytes of field _level 2byte
The number of additional members Typehandler bytes of the Status object instance =4byte
The number of additional members Syncblockindex bytes of the Status object instance =4byte
4+1+4+4=13byte, take into account that the memory block is always in accordance with 4byte memory alignment, so the completion to 16byte.

In summary, the total number of bytes required to create the Sales object instance is 36.

3. Extend 36byte of contiguous space to high addresses on the managed heap and assign memory addresses to them.

4. The initialization of the sales object instance is done.

A: Constructs a type object of sales, and assigns it to the loader heap in the managed heap.
B: Initialize the 2 additional members of the Sales object instance: Typehandler and Syncblockindex. Typehandler points to the method Table,syncblockindex on the load heap to point to synchronization block memory blocks for synchronizing the instance objects in a multithreaded environment.
C: Initialization of the instance field, first initializes the instance field of the System.Object, then the employee, and finally the instance field of sales.

5. Assign the managed heap address of the sales instance object to the thread stack variable _sales.


-Value type Object creation

For value types (excluding instance members of value types in a class), such as structs, created with the new keyword, the object is actually created on the thread stack, which is not controlled by the CLR's garbage collection, but is managed directly by the operating system, and its storage units are automatically freed when the method at which the type instance is located ends. On the thread stack, the operating system maintainer has a stack pointer that points to the address of the next free space.

The memory address of the thread stack is populated from high to low, that is, when the stack is extended from the higher address to the lower address, and the memory is removed from the low address to the high address when the stack is dropped. Use the following code to walk through the process:

 Public void Saysth ()
{
    int a = 1;
    char b = ' x ';
}

1, before the method executes, the thread stack pointer points to a high, such as 100
2, start the execution of the Saysth method, the return address of the Saysth method first into the stack, the thread stack pointer points to a lower position, such as 99
3. Execute int a = 1, allocate 4byte of memory space on the thread stack, save the value 1 in the address space, and the threads stack pointer Move down 4 bytes to a lower position, such as 98
4, execute char b = ' x ', allocate 2byte of memory space on the thread stack, save the value "X" in the address space, and the threading stack pointer moves down 4 bytes to a lower position, such as 97
5, the method execution ends, sequentially last B and a memory, the thread stack pointer back to the return address, that is, 99

→ Garbage Collection

On the managed heap, a design called "GC Roots", which is always reachable, stores references to object instances, these objects in "GC roots" are labeled "Live", and all object instances referenced by "GC Root" are also labeled "Live". The GC keeps looping through this way until an object instance does not reference an object instance. This is like a "node tree", which starts from the root node and loops through the nodes without the child nodes.

At garbage collection time, all object instances that are not marked as "live" are reclaimed, and then the memory space of the managed heap is re-compressed, and the memory space of the managed heap is ready for the next batch of instance objects.

There are different types of "GC root":
Local variables within the current method are treated as "GC root"
Static variables are also considered "GC root"
If a managed object instance needs to be passed to the COM + library, it will also be treated as "GC root"
If an object has a destructor, it will not be recycled at garbage collection time, only when the object is called finalizer, which means that the object with the destructor is considered "GC root"

To improve the efficiency of garbage collection, GC introduces an "age-old" strategy that divides objects in the managed heap into three generations, 0, 1, and 2, respectively. and will set different threshold capacity for different ages, the No. 0 generation about 256KB, 1th generation about 2MB, 2nd generation about 10MB. The newly created object is at first the No. 0 generation, and the GC will always reclaim the No. 0 generation of object instances that are not marked as "live". The specific operation process is as follows:

1. When the CLR initializes, all the objects that are added to the managed heap are No. 0 generation.
2, when there is garbage collection, the object that has not been recycled to increase the age of 1, into the 1th generation.
3, the 1th generation of objects if the threshold capacity is not reached, it will not be recycled, so as to effectively improve the efficiency of garbage collection.
4, only when the No. 0 generation threshold capacity is not enough to create a new object, and the 1th generation object instance size exceeds the 1th generation threshold capacity, the GC will simultaneously reclaim NO. 0 and 1th objects, and not be recycled 1th objects upgraded to 2 generations of objects, not yet recycled No. 0 objects upgraded to 1 generation objects.
5, so repeated.

→ Cleanup of unmanaged resources

For some managed resources, the CLR's garbage collector can help us clean up the memory automatically, and for some unmanaged resources, such as database connections, file handles, COM objects, and so on, still need to be manually cleaned by developers. Please refer here for details.

. NET object creation, garbage collection, and manual processing of unmanaged resources

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.