. NET Compact Framework resource memory released

Source: Internet
Author: User
Tags compact comparison table hosting

I finally started writing this article. A netizen urged me several times. Today I can finally finish it with my mind.

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 for program resources, what should we do 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 reiterate 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:

1. Destructor;

2. Inherits the idisposable interface to implement the dispose method;

3. Provides the close method.

After the previous introduction, we can know that the Destructor can only be GCSo 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 GCSo the Destructor can be used as a remedy. CloseAnd 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 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 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.

The first is the implementation of these three methods, which are roughly as follows:

///

/// The class to show three disposal function

///

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

}

For close, it is not a release in the true sense. Except that it needs to be displayed and called, I will not talk much about it here. 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 running result is as follows:

Dispose called!

For the above disposeclass implementation, GC also needs to call the object's destructor,Follow the preceding stepsGCFor the 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:

///

/// The class to show three disposal function

///

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

}

Use the following code for testing.

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 displayed

Or 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. Provides destructor to prevent resources from being released, mainly non-memory resources;

2. For disposeAnd closeFor 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 disposeYou must add"GC. suppressfinalize (this)"Statement to avoid GCCall 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.

(Converted from yuweng column http://tb.blog.csdn.net/TrackBack.aspx? Postid = 1023352)

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.