IDisposble is used for writing object cleanup functionality for our class.
How to implement?
1. Write Dispose(bool) method
Code :
- Implement IDisposable and define Dispose() to cleanup managed object
- Implement Destructor (Finalizer) to cleanup unmanaged object, do not use Destructor if do not have at least one unmanaged object in class
How to implement?
1. Write Dispose(bool) method
public void Dispose(bool disposing)
{
if (_dispose) return;
if (disposing)
{
//Free managed code
}
//Free unmanged code
_dispose = true;
}
2. Call Dispose(bool) with true method from actual Dispose() method of IDisposable, to release managed object.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
Below statement suppress destructor of the class for managed object.
If we do not write this GC puts some objects in generation 1 and generation 2 also that degrade performance
With this statement GC puts objects in 0th generation that improve performance
GC.SuppressFinalize(this);
3. Call Dispose(bool) with false from destructor to release unmanaged objects.
~clsSecurityCritical() //Finalizer
{
Dispose(false);
}
4. GC.SuppressFinalize(this) Requests that the CLR not call the finalizer for the specified object.Code :
public class clsSecurityCritical : IDisposable
{
public clsSecurityCritical()
{
}
public void CallCheck()
{
Console.WriteLine("Security
Critical code executed");
}
~clsSecurityCritical() //Finalizer
{
Dispose(false);
}
bool _dispose = false;
public void Dispose(bool disposing)
{
if (_dispose) return;
if (disposing)
{
//Free
managed code
}
//Free
unmanged code
_dispose = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
No comments:
Post a Comment