[. Net Object-Oriented programming advanced] (8) hosting and non-hosting, hosting and non-hosting

Source: Internet
Author: User

[. Net Object-Oriented programming advanced] (8) hosting and non-hosting, hosting and non-hosting

This section introduces:Although the vast majority of memory garbage collection during. NET programming is automatically reclaimed by CLR (runtime in public languages), there are also a lot of code collections. Master the basic knowledge of hosting and non-hosting, which can effectively avoid program exceptions in some situations.

1. What is managed and unmanaged?

Managed resources: generally refers to the memory resources controlled by CLR (when the common language is running). These resources are managed by CLR. It can be considered as a resource in the. net class library.

Unmanaged resources: resources that are not controlled and managed by CLR.

GC is responsible for garbage collection for managed resources. For unmanaged resources, GC can track the lifetime of the unmanaged resources, but does not know how to release it. At this time, manual release is required.

2. What resources are not managed?

In general, resources are not controlled and managed by the CLR.

Such resources include file streams, image graphics, database connections, network connections, system Window handles, and printer resources. A group of APIs that can be considered as operating system resources.

Principle: if our classes use unmanaged resources, such as database connections and file handles, these resources need to be released immediately after use.

3. How to release unmanaged resources?

. NET standard practices for releasing resources are as follows:

(1) inherit the IDisposable interface;

(2) Implement the Dispose () method,Release managed and unmanaged resources, and remove the object from the garbage collector (the garbage collector does not recycle the resource );

(3) Implement class destructor,Release unmanaged resources.

Several parameters of the Dispose () method are described as follows:

A. If the parameter is true, all resources are released and can only be called by users.

If the parameter is set to false, the resources are released and can only be automatically called by the garbage collector.

C. If the subclass has its own unmanaged resources, you can reload this function to add the release of its own unmanaged resources.

D. But remember, to overload this function, you must ensure that the base class version is called to ensure the normal release of the base class resources.

4. Example

4.1 Release Database Connection

(1) incorrect practices:

SqlConnection conn = new SqlConnection ();

// Do something;

Conn. Dispose ();

This code segment causes conn. Dispose (); to fail to be executed in a timely manner, resulting in the failure to close the connection in time.

(2) correct practices:

SqlConnection conn = new SqlConnection();try{    //do something;}finally{    conn.Dispose();}

For the above code, we can also simplify the amount of code, c # Use using to simplify the input, the compiler automatically translates it into try... finally, and then write the following code:

(3) improvement practices: 

using(SqlConnection conn = new SqlConnection()){      //do something;}

4.2 comprehensive example of Resource Recovery 

Public class BaseResource: IDisposable {private IntPtr handle; // handle, which belongs to the private System of the unmanaged resource. componentModel. component comp; // Component, managed resource private bool isDisposed = false; // indicates whether the resource has been released // interface implementation method // indicates the call by the class user, release class resource public void Dispose () {Dispose (true); // release managed and unmanaged resources // remove the object from the garbage collector linked list, // when the garbage collector is working, only managed resources are released without executing the Destructor GC of this object. suppressFinalize (this);} // called by the garbage collector to release unmanaged resources ~ BaseResource () {Dispose (false); // release an unmanaged resource} // If the parameter is true, all resources are released, users can only call this function. If the value of // is false, it indicates that unmanaged resources are released and can only be automatically called by the garbage collector. // If the subclass has its own unmanaged resources, you can reload this function, add your own release of unmanaged resources // But remember to reload this function must ensure that the base class version is called, to ensure that the base class resources are normally released protected virtual void Dispose (bool disposing) {if (! This. isDisposed) // if the resource is not released, this judgment mainly uses to prevent objects from being released multiple times {if (disposing) {comp. dispose (); // release managed resources} this. isDisposed = true; // identifies the released object }}

5. Notes for releasing resources

A. The call to the Dispose () method is displayed, which can release resources in time and improve the performance by removing the execution of the Finalize () method;

B. if the Dispose () method is not explicitly called, the garbage collector can also release unmanaged resources through the destructor. The Garbage Collector itself has the function of recycling hosted resources, this ensures the normal release of resources, but the garbage collection will lead to the waste of unmanaged resources not released in time.

C. Use destructor to release resources as little as possible in. NET. Objects without destructor are deleted from the memory during one processing by the spam processor, but the objects with destructor need to be called twice. The first time the Destructor is called, the second time the object is deleted. In addition, a large amount of resource code is included in the destructor, which will reduce the efficiency of the garbage collector and affect the performance.

D. For objects that contain unmanaged resources, it is best to call the Dispose () method in time to recycle resources, instead of relying on the garbage collector.

E. The Destructor can only be called by the garbage collector.

The F. Despose () method can only be called by the class user.

G. In. NET, all classes that inherit the IDisposable interface can use the using statement, so that the system will automatically call the Dispose () method after the scope is exceeded.
H. A resource security class implements the IDisposable interface and destructor. Provides double insurance for manually releasing resources and automatically releasing resources by the system.

6. About Finalize and Dispose

(1) Finalize only releases unmanaged resources;

(2) Dispose releases managed and unmanaged resources;

(3) It is no problem to repeatedly call Finalize and Dispose;

(4) Finalize and Dispose share the same resource release policies, so there is no conflict between them.

7. Key points:

The content in this section is relatively simple. NET managed and unmanaged resources. A vast majority of resources are automatically released by CLR (runtime in public languages), known as managed code. Some resources need to be manually released, known as unmanaged code. Several memory release methods for controlling unmanaged code can effectively avoid program exceptions and reasonably release the memory, facilitating program stability and smoothness.

========================================================== ========================================================== ====================

 Returned directory

<If it is helpful to you, please click here for recommendations. If yes

Do not understand or make a mistakePoints, Please exchange more>

<If you have any difficulty reading this series of articles, please read. net Object-Oriented Programming basics first>

<Reprinted statement: technology requires a spirit of sharing. You are welcome to repost the article in this blog, but please note the copyright and URL>

. NET exchange group: 467189533

========================================================== ========================================================== ====================

Related Article

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.