C # managed and unmanaged Resources

Source: Internet
Author: User

Managed resources are referred to as. NET resources that can be reclaimed automatically, primarily the memory resources allocated on the managed heap. The collection of managed resources does not require manual intervention, and the. NET runtime is recycled in a suitable call to the garbage collector.

Unmanaged resources are referred to as. NET does not know how to recycle resources, the most common type of unmanaged resources is to wrap the operating system resources of objects such as files, Windows, network Connections, database connections, brushes, icons and so on. This type of resource, the garbage collector calls the Object.Finalize () method when it cleans up. By default, the method is empty, and for unmanaged objects, you need to write code in this method that reclaims the unmanaged resources so that the garbage collector correctly reclaims the resources.

In. NET, the Object.Finalize () method cannot be overloaded, and the compiler automatically generates the Object.Finalize () method based on the destructor of the class, so for classes that contain unmanaged resources, you can place the code that frees the unmanaged resources in the destructor.

Note that managed resources cannot be freed in a destructor because the destructor is called by the garbage collector, and it is possible that the managed resources contained by the class have been reclaimed before the destructor call, leading to unpredictable results.

Originally, unmanaged resources can be recycled by the garbage collector, but unmanaged resources are generally limited and valuable, and the garbage collector is automatically called by the CRL, so that unmanaged resources are not guaranteed to be released in a timely manner, so a Dispose () method is defined. Allows the user to manually release unmanaged resources. The Dispose () method frees both the managed and unmanaged resources of the class, and the garbage collector does not recycle this instance again after the consumer calls this method manually. The Dispose () method is called by the consumer, and when invoked, both the managed and unmanaged resources of the class must not be reclaimed, so both resources can be reclaimed at the same time.

Microsoft has specifically defined 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 practice for resource deallocation is:

(1) Inherit IDisposable interface;

(2) Implement the Dispose () method, in which the managed and unmanaged resources are freed, and the object itself is removed from the garbage collector (the garbage collector is not reclaiming this resource);

(3) Implement a class destructor in which to release unmanaged resources.

When used, the display calls the Dispose () method, which releases resources in a timely manner, improves performance by removing the execution of the Finalize () method, and if the call to Dispose () method is not displayed, the garbage collector can also release unmanaged resources through destructors. The garbage collector itself has the ability to reclaim managed resources, guaranteeing the normal release of resources, except that recycling by the garbage collector can lead to a waste of non-timely releases of unmanaged resources.

In. NET, you should use as little as possible to free up resources with destructors. Objects without destructors are removed from memory in a single processing of a garbage processor, but objects with destructors require two of times, the first time the destructor is called, and the object is deleted the second time. And having a large number of release resource codes in a destructor can reduce the efficiency of the garbage collector and affect performance. So for objects that contain unmanaged resources, it is best to call the Dispose () method in a timely manner to reclaim resources instead of relying on the garbage collector.

There it is. NET is a resource-freeing mechanism for classes that contain unmanaged resources, and the class is a resource-safe class as long as the code is written according to the steps required above.

Here is an example to summarize. NET unmanaged resource recovery mechanism:

public class Baseresource:idisposable

{

Privateintptr handle; Handle, which belongs to an unmanaged resource

Privatecomponet comp; components, managed resources

Privateboo isdisposed = false; Flag of whether the resource has been freed

Publicbaseresource

{

}

Implementing interface Methods

By the consumer of the class, the call is displayed externally, releasing the class resource

Publicvoid Dispose ()

{

Dispose (true);//releasing managed and unmanaged resources

Removes an object from the list of garbage collector chains.

Thus, when the garbage collector works, only the managed resources are freed, not the destructor of this object

Gc. SuppressFinalize (this);

}

Called by the garbage collector to release unmanaged resources

~baseresource ()

{

Dispose (false);//Release unmanaged Resources

}

A parameter of true means that all resources are freed and can only be invoked by the consumer

A parameter of false means that the unmanaged resource is freed and can only be called automatically by the garbage collector

If the subclass has its own unmanaged resource, you can overload the function to add your own unmanaged resource's release

Remember, however, that overloading this function must ensure that the base class's version is called to ensure that the base class's resources are properly freed

protectedvirtual void Dispose (bool disposing)

{

if (!this.disposed)//If the resource is not released this decision is mainly used to prevent the object from being released multiple times.

{

If (disposing)

{

Comp.dispose ();//Release managed resources

}

CloseHandle (handle);//Release unmanaged Resources

Handle= IntPtr.Zero;

}

this.disposed= true; Identifies that this object has been disposed

}

}


Destructors can only be called by the garbage collector.

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

In C #, any class that inherits the IDisposable interface can use a using statement, allowing the system to call the Dispose () method automatically after it goes out of scope.
A resource-safe class that implements the IDisposable interface and destructor. Provides manual release of resources and automatic release of resources by the system.

The original text goes to: http://blog.csdn.net/zlwzlwzlw/article/details/7918633

C # managed and unmanaged Resources

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.