Sunday, June 9, 2013

Dispose & IDisposable in C#

The Dispose method in .Net is used to clear out un-managed resources like file stream, database connection etc once an objects goes out of scope.

In .Net resources are not clear immediately, when they go out of scope, instead they are maintained in the Managed Heap and wait for Garbage Collection to run and clear the resources. However network, resources like file stream and database connections wait till Garbage Collection runs and releases them, these resources are shared and should be freed as soon as possible for other objects to use them, hence .Net introduces a special method called the Dispose() method which can be used to clear all such un-managed resources.
All classes which deal with un-managed resources should implement the IDisposable interface and override the Dispose() method. In the Dispose() method implementation the class should clear out all the un-managed resources used in the class. Programs or methods using instances of these classes should make sure that they call the dispose method of the object once it completes using the object, this will ensure that all un-managed resources are freed at the earliest.

The following class implements the IDisposable interface and overrides the Dispose() method to clear un-managed resources.

public class mySharedResource : IDisposable
{       
// Class variables and methods
            
public void Dispose()
       
{
           
// Dispose un-managed resources here.
           
GC.SuppressFinalize(this);
}}

The following lines of code, create an instance of the class, calls its methods and finally calls the Dispose method to clear the un-managed resources in the class.

mySharedResource objSharedResource = new mySharedResource();
// Call the class methods using the object objSharedResource
// Once done call the Dispose method to clear the resources.


objSharedResource.Dispose();


Notice that the GC.SuppressFinalize
is called from the Dispose method implementation; this makes sure that Finalize is not called for this object when Garbage Collection runs, Garbage Collection need not call Finalize since the resources are already disposed.


Search Flipkart Products:
Flipkart.com

No comments: