C # resource release

Source: Internet
Author: User
Document directory
  • C # resource release
C # the release of resources finally began to write this article. A netizen urged me several times. Today, I can finally calm down and complete it. To facilitate the development of articles, we need to clarify two concepts first. First, many people use. Net to write programs and talk about hosting. So what does. Net mean by resource hosting? Is it relative to all resources, or is it limited to some resources? Many people do not know much about this, Actually. NetThe hosting is only for memory, not for all resources; therefore, for stream, Database connection, GDI +And com.Objects. These resources are not affected by. net.Management. For memory release and recovery, the system provides GC-Garbage CollectorOther resources must be manually released.In my previous articles, I learned that the. NET type is divided into two categories: Value Type and reference type. The former is allocated to the stack and does not require GC collection; the latter is allocated to the stack. Therefore, the memory release and recovery must be completed through GC. GC is called "Garbage Collector". As its name implies, it is a garbage collector. Only objects called garbage can be recycled by GC. That is to say, The memory occupied by a reference type object needs to beGCGarbage collection is required first. So. netHow can I determine that a reference type object is spam?. netAs long as it is determined that this object or its contained Sub-objects are not referenced by any reference, the system considers it as garbage.After clarifying these two basic concepts, let's talk about how GC works and its functions. The release and recovery of memory must be accompanied by program running. Therefore, the system schedules independent threads for GC. GC generally queries whether objects in the memory become garbage and then releases and recycles the garbage. Therefore, GC uses a certain priority algorithm to recycle memory resources. Second, There are two types of garbage in the memory: one is to call the destructor of the object, and the other is not to call.GCThe collection of the former requires two steps. The first step is to call the object's destructor, and the second step is to recycle the memory, but note that these two steps are not performed in the GCTwo rounds are required for one round robin. Compared with the latter, the memory is only recycled.It is clearly known that for a specific resource, you cannot know exactly when the object destructor will be called, and when the GC will release and recycle the memory it occupies. For programmers who have switched from languages such as C and C ++, the concept should be changed here. So what should we do for program resources, and how to do it, in order to make the program more efficient, while occupying resources can be released as soon as possible. As mentioned above, there are two types of resources: managed memory resources, which do not require us to worry about. The system has already managed for us. For unmanaged resources, here we will re-declare that stream, database connection, related objects of GDI +, and COM objects need to be manually released. How should we release these operations .. NET provides three methods, which are also the most common, roughly as follows: <! -- [If! Supportlists] --> 1. <! -- [Endif] --> destructor; <! -- [If! Supportlists] --> 2. <! -- [Endif] --> inherits the idisposable interface and implements the dispose method. <! -- [If! Supportlists] --> 3. <! -- [Endif] --> provides the close method. After the previous introduction, we can know that the Destructor can only be GC So it is not reasonable to use it as a resource release because the resource release is not timely; but to prevent resource leakage, after all, it will be GC So the Destructor can be used as a remedy. Close And dispose The difference between the two methods is that the close of the object is called. This object may be re-used; and Dispose Method, the resource occupied by the object needs to be marked as useless, that is, the object is destroyed and cannot be used again.For example, for the common sqlconnection class, after the close method is called, you can re-open the database connection through open. When this object is completely unnecessary, you can call the dispose method to mark this object as useless, wait for GC to return. After understanding the meaning of the two methods, do not distort the meaning of the two methods when you add interfaces to your own classes. Next, let's talk about the call times of these three functions. I will explain them with a few experimental results, which may make you more impressed. First, the implementation of these three methods is roughly as follows: /// <summary> // the class to show three disposal function // </Summary> public class disposeclass: idisposable {public void close () {debug. writeline ("Close called! ");}~ Disposeclass () {Debug. writeline ("destructor called! ") ;}# Region idisposable members public void dispose () {// todo: Add disposeclass. Dispose implementation Debug. writeline (" dispose called! ") ;}# Endregion} is not a release in the true sense for close. I will not talk much about it here except to note that it needs to be displayed and called. The Destructor is not executed immediately after the object leaves the scope. It is called only when the process is disabled or the GC. Collect method is called. See the following code execution result. Private void create () {disposeclass myclass = new disposeclass ();} private void callgc () {GC. collect ();} // show destructor create (); debug. writeline ("after created! "); Callgc (); the running result is: After created! Destructor called!Apparently, except for the create function, The destructor of the myclass object is not called immediately, but is called only when GC. Collect is called. For dispose, you also need to display the call, but for type objects that inherit idisposable, you can use the Using Keyword, so that the dispose method of the object will be automatically called after the using range exists. For example: Using (disposeclass myclass = new disposeclass () {// other operation here} The above running result is as follows: Dispose called!For the above disposeclass class implementation, GC also needs to call the object's destructor, Follow the preceding stepsGCFor the stream process, GCFor an object that needs to call the destructor, at least two steps are taken, that is, the object's destructor is called first, and the memory is recycled. That is to say, according to the disposeFunction, although executed, but GCStill need to execute the destructor, then a complete disposeFunction, you should call GC. suppressfinalize (this)To tell GCSo that it no longer needs to call the object's destructor.The modified disposeclass is as follows:/// <Summary> // the class to show three disposal function // </Summary> public class disposeclass: idisposable {public void close () {debug. writeline ("Close called! ");}~ Disposeclass () {Debug. writeline ("destructor called! ") ;}# Region idisposable members public void dispose () {// todo: Add disposeclass. Dispose implementation Debug. writeline (" dispose called! "); GC. suppressfinalize (this) ;}# endregion} is tested using the following code. Private void run () {using (disposeclass myclass = new disposeclass () {// other operation here} private void callgc () {GC. collect ();} // show destructor run (); debug. writeline ("after run! "); Callgc (); the running result is as follows: Dispose called! After run!Obviously, the object's destructor is not called. Through the above experiment and text instructions, you will get the following comparison table.
  Destructor DisposeMethod CloseMethod
Meaning Destroy object Destroy object Disable object Resources
Call Method Cannot be displayed and called. It will be GCCall Call to be displayedOr use usingStatement Call to be displayed
Call time Uncertain Are you sure you want to call or exit usingProgram block OK.
When defining a type, do you have to implement these three functions. My suggestions are as follows.<! -- [If! Supportlists] --> 1.<! -- [Endif] --> Provides destructor to prevent resources from being released, mainly non-memory resources;<! -- [If! Supportlists] --> 2.<! -- [Endif] --> For dispose And close For the method, you need to check the resources used by the defined type (see the previous section) and decide whether to define the two functions;<! -- [If! Supportlists] --> 3.<! -- [Endif] --> In the implementation of dispose You must add" GC. suppressfinalize (this) "Statement to avoid GC Call the destructor of an object.C # The memory used by the program is hosted, but it does not mean abuse. Good Programming habits are conducive to improving the code quality and program running efficiency.

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.