.NET garbage collection

xiaoxiao2021-03-06  79

Recently, I saw the knowledge of garbage collection related to .NET, I feel that this paper summarizes this, share the netizens of .NET garbage collection, draw on Java garbage collection mechanism. In the previous Windows environment, we will often forget to release the already useless memory, or try to use the released memory, causing the crash of the program. However, as the garbage recovery mechanism in .NET appears, this situation has been greatly improved. In .NET, two variable types, one is the value type, one is the memory of the reference type, value type, stored on the current thread, the garbage collection is not responsible for recycling this area, the current method is running The memory will be released automatically. The memory of the reference type is placed on the hosted stack, and the garbage collection of .NET is responsible for recycling memory resources in this area. In .NET, three modes are available to recover memory resources: Dispose mode, Finalize method, and close method. Dispose provides a way to show the release of memory resources. The Dispose call method is: The resource object to be released. Disposefinalize method is a method of releasing memory resources within .NET. This method is not open to the outside, which is called by the garbage collection. CLOSE and DISPOSE are actually the same, but there is no way to provide Dispose, only the close method is provided, and Close is actually in the class of the object, and it is still called a private Dispose method, and Finalize is actually called one DISPOSE method

So since .NET has a Finalize method in garbage collection, then why do you have to provide Dispose methods and close methods? This is because the Finalize method releases the hosted stack memory and non-hosting memory. Dispose will only release the unmanaged memory resources, which will not be released for managed memory resources, can only be released by garbage collection. When we open a database connection (this is a non-hosting memory resource), if we don't manually release this part of the resource, wait for the next garbage recycling to recycle resources, then it may be a long time, so Use the method of Dispose. So after we use SqlConnection, after connecting the database, after calling the SqlConnnection.Dispose method, you can disconnect from the database, but SQLConnection does not die, this object can continue to use until the next garbage collection calls Finalize method Recycling resources.

转载请注明原文地址:https://www.9cbs.com/read-120825.html

New Post(0)