finalize vs dispose method in .net, difference between finalize and dispose method, when to use finalize and dispose method
.NET Framework provides two methods Finalize and Dispose for releasing unmanaged resources like files, database connections, COM etc. This article helps you to understand the difference between Finalize and Dispose method.
Difference between Finalize & Dispose Method
Finalize
Used to free unmanaged resources like files, database connections, COM etc. held by an object before that object is destroyed.
Internally, it is called by Garbage Collector and cannot be called by user code.
It belongs to Object class.
Implement it when you have unmanaged resources in your code, and want to make sure that these resources are freed when the Garbage collection happens.
There is performance costs associated with Finalize method.
For Example,
// Implementing Finalize method
publicclassMyClass
{//Automatically Converted to Finalize method.
{//Automatically Converted to Finalize method.
~MyClass()
{
// Code
}}
Dispose
It is used to free unmanaged resources like files, database connections, COM etc. at any time.
Explicitly, it is called by user code and the class implementing dispose method must implement IDisposable interface.
It belongs to IDisposable interface.
Implement this when you are writing a custom class that will be used by other users.
There is no performance costs associated with Dispose method.
For Example,
Implementing Dispose method
public class MyClass : IDisposable
{
{
private bool disposed = false;
//Implement IDisposable.
public void Dispose()
{ Dispose(true); }
protected virtual void Dispose(bool disposing)
{
if (!disposed) {
if (disposing) {
// clean up managed objects }
// clean up unmanaged objects disposed = true; } }}
//Implement IDisposable.
public void Dispose()
{ Dispose(true); }
protected virtual void Dispose(bool disposing)
{
if (!disposed) {
if (disposing) {
// clean up managed objects }
// clean up unmanaged objects disposed = true; } }}
Using Dispose and Finalize methodpublic class MyClass : IDisposable{
private bool disposed = false; //Implement IDisposable.
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{ // clean up managed objects }
// clean up unmanaged objects disposed = true; } }
//Automatically Converted to Finalize method ~MyClass()
{ Dispose(false); }}
private bool disposed = false; //Implement IDisposable.
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{ // clean up managed objects }
// clean up unmanaged objects disposed = true; } }
//Automatically Converted to Finalize method ~MyClass()
{ Dispose(false); }}
No comments:
Post a Comment