.Net C# Development

Dispose and Finalize

Dispose

 Garbage collector (GC) plays the main and important role in .NET for memory management so programmer can focus on the application functionality. Garbage collector is responsible for releasing the memory (objects) that is not being used by the application. But GC has limitation that, it can reclaim or release only memory which is used by managed resources. There are a couple of resources which GC is not able to release as it doesn’t have information that, how to claim memory from those resources like File handlers, window handlers, network sockets, database connections etc. If your application these resources than it’s programs responsibility to release unmanaged resources. For example, if we open a file in our program and not closed it after processing than that file will not be available for other operation or it is being used by other application than they can not open or modify that file. For this purpose FileStream class provides Dispose method. We must call this method after file processing finished. Otherwise it will through exception Access Denied or file is being used by other program. 

Close Vs Dispose

 Some objects expose Close and Dispose two methods. For Stream classes both serve the same purpose. Dispose method calls Close method inside.

void Dispose()   
{  
    this.Close();  
}  

But for some classes both methods behave slightly different. For example Connection class. If Close method is called than it will disconnect with database and release all resources being used by the connection object and Open method will reconnect it again with database without reinitializing the connection object. HoweverDispose method completely release the connection object and cannot be reopen just calling Open method. We will have re-initialize the Connection object.

Creating Dispose

 To implement Dispose method for your custom class, you need to implement IDisposable interface. IDisposable interface expose Dispose method where code to release unmanaged resource will be written.

public class MyClass: IDisposable {  
  
    //Construcotr   
    public MyClass() {  
        //Initialization:   
    }  
  
    //Destrucor also called Finalize   
    ~MyClass() {  
        this.Dispose();  
    }  
  
    public void Dispose() {  
        //write code to release unmanaged resource.   
    }  
}  

Finalize

 Finalize method also called destructor to the class. Finalize method can not be called explicitly in the code. Only Garbage collector can call the the Finalize when object become inaccessible. Finalize method cannot be implemented directly it can only be implement via declaring destructor. Above class illustrate, how to declare destructor. It is recommend that implement Finalize and Dispose method together if you need to implement Finalize method. After compilation destructor becomes Finalize method.

Leave a Reply

Your email address will not be published. Required fields are marked *