Thursday, December 20, 2007

IDisposable interface...

Introduction

it is our responsibilty as a coder that whatever the resources we are taking from system, we have to give back to it....
but today in CLR it is duty of GC (Garbage collector)...
but this is very expensive method and it can harm the application performacne, no doubt it is very good idea to leave on GC if you are beginners, but if you are experts then always give back what ever resources we have taken from system immediatly after their use...

for that we can use IDisposable interface to release any resources...
use this code in each and every class declaration...

public class MyClass : IDisposable
{
#region "IDisposable Members"
private bool disposed = false;
public new void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

private void Dispose(bool disposing)
{
if (!this.disposed)
{
try
{
if (disposing)
{
//write code to release all resources taken by class..
// like..
// if(mythread != null)
// mythread.abort();
// mythread = null.....
}
}
finally
{
base.Dispose();
}
}
disposed = true;
}

~OpenFT()
{
Dispose(false);
}

#endregion
}

No comments: