Talking about resource release in C # hosting program

Source: Internet
Author: User
Tags comparison table
Loading data ......

Used. net tool to write programs, it is not difficult to find that it has a benefit, that is, the memory used does not need to be released, especially when using C # Or VB. net to write programs, because the memory occupied by the program is managed by the system, so the release of memory does not require the programmer to worry about. Many people have transformed from C language or C ++ language. This is often not suitable, for example, when defining an array or going to a new object, they are used to releasing it with the Delete statement after use. However, similar statements are not provided in C # For the same operation. Someone may ask if. Net does not need to release the memory, or if it wants to display how to release an object. So what I want to clearly tell you is that in C #The memory is recycled by GC.In the program, we can only mark the current object as it is no longer referenced.It is uncertain when to recycle the memory, because it is time-consuming and laborious to recycle the memory. The possibility of triggering is that the memory is insufficient or the GC. Collect call is displayed.). After understanding this, when we write a program, when the defined type uses a relatively large memory resource or resources that may cause operation conflicts, for example: various connection objects and various streamsObject, various graph-related objects, various mutex objects, etc. You need to provide interfaces to close and mark the objects, so asEfficiency can be improved during recycling.. Net provides three methods, which are also the most common, roughly as follows: 1. destructor; 2. inherit the IDisposable interface to implement the Dispose method; 3. Provide the Close method. For destructor, people who use C # For A Long Time will forget it. Or when C # is used to write a class, the class destructor are rarely written. For the C # destructor, the meaning of the original C ++ is basically extended. HoweverC #Cannot be like C ++In this way, when an object is deleted, the object's destructor is called when GCThis object will be called only when it is detected that it is no longer referenced. For GCIt is uncertain when to detect and collect, so the time for calling the object's destructor is also uncertain. This also hides the truth that it is not reasonable to close and mark some resources in the destructor, because the occupied resources cannot be quickly closed or marked as useless.The Destructor cannot display the call. For the last two methods, the display call is required to be executed. WhileCloseAnd DisposeThe difference between the two methods is that the Close of the object is called.This object may be re-used; and DisposeMethod, the resources occupied by this object need to be marked as useless, that is, the object is to be destroyed and cannot be used again.For example, common. the SqlConnection class in the. Net class library. After the Close method is called, you can re-Open a 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 collection. 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 bring you a deeper impression. 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!So for the above Dispose implementation of the DisposeClass type, in fact, it does not achieve the purpose of marking the memory useless, that is, the object's destructor will be called. Someone asks, since the Dispose method does not reference the object to indicate that the object is no longer referenced, it makes no sense to call the object's destructor. Can you add processing in Dispose, to avoid calling the destructor. The answer is yes. You need to add the GC. SupdivssFinalize (this) Statement in the Dispose method. 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. SupdivssFinalize (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 in GCRecycling is called 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. 1. Generally, do not provide destructor because they cannot be executed in time; 2. 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; 3. In the implementation of Dispose You must add" GC. SupdivssFinalize (this) "Statement.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.

Source: http://blog.csdn.net/kong1122/archive/2007/08/02/1722685.aspx

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.