The difference between using managed and unmanaged resources in C #, and how to manually release unmanaged resources :,

Source: Internet
Author: User

[Switch] the difference between using managed and unmanaged resources in C # And how to manually release unmanaged resources :,

Managed resources refer to. NET resources that can be automatically recycled, mainly the memory resources allocated on the managed stack. The collection of managed resources does not require manual intervention. Some. NET runtime Libraries call the Garbage Collector to recycle the resources.

Unmanaged resources refer. NET does not know how to recycle resources. The most common type of unmanaged resources are the objects that encapsulate operating system resources, such as files, windows, network connections, database connections, image brushes, and icons. This type of resource, the garbage collector will call the Object. Finalize () method during cleaning. By default, the method is empty. For unmanaged objects, you need to write code to recycle unmanaged resources in this method so that the garbage collector can correctly Recycle resources.

In. NET, Object. the Finalize () method cannot be overloaded. The Compiler automatically generates an Object based on the class destructor. the Finalize () method. Therefore, for classes that contain unmanaged resources, you can place the code that releases the unmanaged Resources in the destructor.

Note: The managed resources cannot be released in the destructor. Because the Destructor are called by the garbage collector, it may be before the Destructor is called, the managed resources contained in the class have been recycled, leading to unpredictable results.

If we follow the above practice, the unmanaged resources can also be recycled by the garbage collector, but the unmanaged resources are generally limited and valuable, and the garbage collector is automatically called by the CRL, in this way, the release of unmanaged resources cannot be guaranteed in a timely manner. Therefore, a Dispose () method is defined to allow users to manually release the unmanaged resources. The Dispose () method releases the managed and unmanaged resources of the class. After you manually call this method, the garbage collector does not recycle such instances. The Dispose () method is called by the user. During the call, the managed and unmanaged resources of the class are certainly not recycled, so the two types of resources can be recycled at the same time.

Microsoft specifically defines an interface for the collection of unmanaged resources: IDisposable, which contains only one Dispose () method. Any class that contains unmanaged resources should inherit this interface.

In a class that contains unmanaged resources, the standard practices for resource release 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 this resource );

(3) Implement class destructor to release unmanaged resources.

In use, the call of the Dispose () method is displayed to release resources in time, and the execution of the Finalize () method is removed to Improve the Performance. If the call of the Dispose () method is not displayed, the garbage collector can also use destructor to release unmanaged resources. The Garbage Collector itself has the function of recycling managed resources to ensure normal resource release, however, recycling by the garbage collector will lead to the waste of unmanaged resources not released in time.

In. NET, you should use the destructor to release resources as little as possible. 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. Therefore, for objects that contain unmanaged resources, it is best to call the Dispose () method in time to recycle resources, rather than relying on the garbage collector.

The above is the resource release mechanism for Classes containing unmanaged resources in. NET. As long as the code is written according to the steps required above, the class is a class of resource security.

The following uses an example to summarize the. NET unmanaged resource recovery mechanism:

Public class BaseResource: IDisposable


Private IntPtr handle; // handle, which belongs to an unmanaged Resource

Private Componet comp; // component, hosting Resources

Private bool isDisposed = false; // indicates whether the resource has been released.




// Interface Implementation Method

// The class user calls the class externally and releases the class resources.

Publicvoid Dispose ()


Dispose (true); // release managed and unmanaged Resources

// Remove the object from the linked list of the garbage collector,

// When the garbage collector is working, only managed resources are released without executing the destructor of this object.

GC. SuppressFinalize (this );


// Called by the garbage collector to release unmanaged Resources

~ BaseResource ()


Dispose (false); // release unmanaged Resources


// 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.

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

// 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.

Protectedvirtual void Dispose (bool disposing)


If (! This. disposed) // If the resource is not released, this judgment is mainly used to prevent objects from being released multiple times.


If (disposing)


Comp. Dispose (); // release managed resources


CloseHandle (handle); // releases unmanaged Resources

Handle = IntPtr. Zero;


This. disposed = true; // identifies that this object has been released



The Destructor can only be called by the garbage collector.

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

In C #, all classes that inherit the IDisposable interface can use the using statement, so that the system automatically calls the Dispose () method after the scope is exceeded.
A resource security class implements the IDisposable interface and destructor.

Provides double insurance for manually releasing resources and automatically releasing resources by the system.

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: 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.