In. net, automatic memory management is performed by the garbage collector, and GC automatically manages the managed heap.
Recovery of managed resources:
1. How to recycle
This part is mainly recycled by GC. The Garbage Collector is using the root pointer list to obtain the object graph in the managed heap, which defines the managed heap object referenced by the application root. When it starts, it assumes that all objects are recoverable, and starts to traverse all the roots, marking the objects referenced by the root as reachable objects. During the traversal process, if other objects are referenced by the root object, the object is added to the reachable object graph. By analogy, recursive traversal can find all reachable objects to form an accessible object graph. At the same time, inaccessible objects are considered recyclable objects. (Tagging and clear algorithms)
2. When to recycle
(1) When the memory is insufficient to overflow, it is more accurate to say that the 0th generation object is full.
(2) Call the GC. Collect method to forcibly execute garbage collection.
(3) When Windows reports insufficient memory, CLR forcibly executes garbage collection.
(4) When CLR unmounts the AppDomain, GC recycles all the older objects.
(5) other situations, such as insufficient physical memory...
3. After recycling
After garbage collection is performed by GC, multiple "holes" of the collected objects will appear on the heap to avoid chunks in the managed heap. Will re-allocate the memory and compress the managed heap. This process will definitely affect the GC recovery system performance. The CLR Garbage Collector uses the concept of Generation to improve performance.
Unmanaged resource cleanup:
Common unmanaged resources include database connection, file handle, network connection, mutex, COM Object, socket, bitmap, and GDI + object.
There are two main methods: Finalize method and Dispose method.
The two methods have the following rules:
(1) For the cleanup of unmanaged resources, Finalize is automatically called by GC, while Dispose is forcibly called by developers.
(2) try to avoid using Finalize to clean up resources. When necessary, the Dispose method should also be implemented. To provide display call control.
(3) The Finalize and Dispose methods can only clear unmanaged resources, and the GC is still responsible for releasing the memory.
(4) After the object is used up, its resources should be released immediately. It is better to call the Dispose method for implementation.