Class (2)-deconstruct function and garbage collection, deconstruct garbage collection
After defining a class, we can create any number of objects. In this case, the memory allocation on the managed heap and stack will be generated, and a new space will be opened in the heap to store class objects, while the stack will only store references. In general, garbage collection and memory management are only relative to managed heaps. C # memory management is very convenient-that is, there is no need to manage it, and the garbage collector will be responsible for all the work. Several issues need to be clarified about garbage collection.
What is spam? Generally, an object is treated as spam if it is inaccessible to any part of the code.
When the garbage collector works: when it deems it necessary (detailed below) or when the user calls.
The garbage collector does not care about unmanaged resources. What should I do: write code and release it by myself. There are two methods: finalize and dispose.
Basic Concepts
The managed heap stores a pointer indicating the location where the next object will be allocated. When the system runs the new Keyword, The newobj command will be added to the pencil, it is responsible for the following work:
1. Calculate the total memory size required for the new object to be allocated, including all its own members and base classes.
2. check the pointer on the managed heap to determine whether the managed heap has enough memory to allocate the object. If there is enough, start to execute static and common constructors, then return the reference (pointing to the previous position of the pointer to the next object)
3. Move the managed heap pointer to the next available location
4.If the Second Step finds that the space is insufficient, a garbage collection is performed.
Note: Setting the object to null does not cause garbage collection, or clear the space on the managed stack. This only removes the Association (reference) between the object and the managed heap, that is, the object does not point to anything on the managed heap.
Basic Algorithms
When garbage collection is performed, the runtime checks the objects in the managed heap to determine whether the application can still access them. The whole garbage collection is divided into two steps.
Phase 1: Mark-Sweep indicates the clear stage. Assume that all objects in heap can be recycled, find out objects that cannot be recycled, and Mark these objects, finally, all objects not marked in heap can be recycled.
The Garbage CollectorCheck the root of the applicationTo determine the objects that are no longer in use. Simply put, the root is a storage location that stores references to an object hosted on the heap (that is, the two arrows in ). Each application has a set of roots, which are stored in a list. Each root can reference objects in the managed heap or set to null.
The garbage collector can access the list of active root, check the application root against this list, and create a chart in this process, containing all objects that can be accessed from these root. Objects not in the chart cannot be accessed from the application root. The garbage collector will consider marking inaccessible objects as spam and releasing the allocated memory for them. In, since c2 is set to Null and no root points to c2 in the managed heap, it will be treated as garbage.
Phase 2: Compact compression stage. After all the garbage is marked, their memory space is released. The memory space becomes discontinuous and these objects are moved in the heap, this allows them to re-arrange from the heap base address, similar to the disk space fragmentation.
Improvement of garbage collection algorithms-generation
It takes a lot of time to scan all objects for garbage collection. To optimize this process, a generational algorithm is introduced. The essence of the generational algorithm is"The longer an object exists, the more important it may be. the more likely it is to be retained.".
. NET divides the heap into three age zones: Gen 0, Gen 1, and Gen 2;
All objects are stored in the 0th generation. If Gen 0 heap memory reaches the threshold, the 0-generation GC is triggered (only the 0-generation object is scanned). After the 0-generation GC, the surviving objects in Gen 0 enter gen1. If the memory of Gen 1 reaches the threshold value, 1 generation GC is performed. 1 generation GC recycles Gen 0 heap and Gen 1 heap together, and the surviving object enters gen2. The two generations of GC collect Gen 0 heap, Gen 1 heap and Gen 2 heap together. Gen 0 and Gen 1 are relatively small, and the age of these two generations is always around 16 Mb; the size of Gen2 is determined by the application and may reach several GB. Therefore, the cost of the 0-and 1-generation GC is very low, and the 2-generation GC is called full GC, which is usually very high. A rough calculation of 0-and 1-generation GC should be completed in milliseconds to dozens of milliseconds. When Gen 2 heap is large, full GC may take several seconds. In general, the GC frequency of generation 2, Generation 1, and generation 0 should be roughly during. NET application running.
With the generational algorithm, the program does not need to scan all objects.
Http://www.cnblogs.com/springyangwc/archive/2011/06/13/2080149.html)
Others
Garbage collection usually does not require manual intervention, but there are a few exceptions. Because garbage collection only applies to managed objects (more accurately, it only appliesTerminable object) For unmanaged objects, there are many resources that cannot be controlled or managed by CLR, such as file streams, database connections, system Window handles, printer resources, etc ...... These resources generally do not exist in Heap (where the memory is used to store object instances. We still need to release the memory ourselves if we do not enjoy garbage collection. At this time, we have many options. For example, we will anticipate several large resources to be created, and the system may not have so many resources on the hosting stack, so we can do the following:
1. Forcibly call garbage collection to clear all useless managed objects on the managed Stack
2. Use dispose () or implement the IDisposable interface for any object to make the object manageable, and then explicitly or implicitly call dispose () to precisely kill the object.
3. Implement finalize () method for unmanaged objects (Only one deconstruct function can be defined.) To change the objectTerminable, And thenThis object will be able to enjoy the automatic removal benefit of the garbage collector.
2 and 3 can be merged, which is also a standard practice.
Forced garbage collection
The GC. Collect method must be called to forcibly recycle garbage. This method has an overloaded version. You can specify the recycle generation. After this method is called, you can immediately call WaitForPendingFinalizers () to determine whether allTerminable objectAll necessary cleanup tasks must be performed.
Override Finalize method
In fact, we can't override Finalize method. We can only implement this by defining a deconstruct function implicitly, because when the compiler executes the deconstruct function, you will add a lot of code in the finalize method that is implicitly rewritten. We can add code in the deconstruct function to clear unmanaged resources, or even print things to the console. However, the execution time of the deconstruct function is unpredictable (during garbage collection ). After defining a deconstruct function for an unmanaged object, it becomes terminable, and then we can expect the system to handle it in the same way as the hosted object.However, this method is relatively passive (still waiting for garbage collection). If you want to actively clear the method, you need to implement the IDisposable interface to make the object manageable, then explicitly or implicitly call dispose ().
Deconstruct functions (Terminator) and dispose ()
Http://www.cnblogs.com/luminji/archive/2011/03/29/1997812.html)
If our type uses unmanaged resources or requires explicit release of managed resources, it is bestLet the type inheritance interface IDisposable.This is equivalent to telling the caller that this type requires explicit resource release and you need to call my Dispose method. Calling dispose is irrelevant to garbage collection, and does not automatically call dispose (). Therefore, if you remember to call the function, you do not need to call the deconstruct function. If you forget to call the function, you need to solve the problem (the formal method is to do this ). Generally, you can use the using block to enable the system to call dispose by itself (after leaving the using block ).
Formal disposal method
Microsoft defined a formal disposal mode for releasing resources. It noticed the following issues:
1. You can call dispose () multiple times without any problem (if you have already called it, re-calling should not trigger the cleaning process)
2. If dispose () is called, you do not need to call the terminator again.
3. objects are both terminable and can actively release memory.
Class BaseClass: IDisposable {bool disposed = false; // public void Dispose () {// public void Dispose () for garbage collection Dispose (true); // notify garbage collection that the Terminator is no longer called, because we have manually released the memory GC. suppressFinalize (this);} // internal protected virtual void Dispose (bool disposing) {if (disposed) return; if (disposing) {// clear managed resources} // clear unmanaged resources // Let the type know that it has been released disposed = true;} // <summary> // required, in case that the programmer forgets to explicitly call the Dispose method /// </summary> ~ BaseClass () {// It must be false Dispose (false );}}
The constructor is a special function with the same name as the class. It must be preceded by a Tilde ~. All the meaning of providing the deconstruct function is that callers who cannot expect the type will certainly take the initiative to call the Dispose method. Based on the characteristics that the deconstruct function will be called by the garbage collector, the Terminator is used to remedy the resource release.