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 , theobject.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 code that frees unmanaged resources in a 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, thus defining a Dispose () method, which allows the consumer 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, belongs to unmanaged resource

privatecomponet Comp;//components, managed resources

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

Publicbaseresource

         {

         }

//Implement Interface method

//By the consumer of the class, displaying the call externally, releasing the class resource

publicvoid Dispose ()

              {

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

                     

//Remove the object from the garbage collector's linked list,

//So that only managed resources are freed while the garbage collector is working, not destructors for this object

GC. SuppressFinalize (this);

            }

//Called by the garbage collector to release unmanaged resources

~baseresource ()

            {

Dispose (false);//release unmanaged Resources

            }

The //parameter is true to release all resources and can only be invoked by the consumer

The //parameter is false to dispose of unmanaged resources 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

///But remember, overloading this function must guarantee 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.

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.