Saturday, March 27, 2010

03:27: Dispose Pattern In C# (ZT)

 

When we give application to client, we dont know how will he use that whether he will call dispose or not?
It may be missing at client side so our application should be smart enough to free used resources, here is code
which will give Idea to implement finalizer and dispose in same class to take care of resource cleaning.

 

class  DisposePatternInstance : IDisposable
{
private bool IsUnManagedResourceDisposed = false;

~DisposePatternInstance ()
{
Dispose(false); // means only clean up unmanaged resource
}

protected void Dispose(bool IsReleaseMangedResource)
{
if (IsReleaseMangedResource) // clean up managed resource
{
// Code to dispose the managed resources of the class
}


      


if( !IsUnManagedResourceDisposed) // clean up unmanaged resource if it is not released before
{


// Code to dispose the un-managed resources of the class


IsUnManagedResourceDisposed=true;


}




           }

public void Dispose()
{
Dispose(true); // to clean up both managed and unmaned resources



GC.SuppressFinalize(this); //If dispose is called already then say GC to skip finalize on this instance
}
}




 




  • Finalize() is implicitly clean up unmanaged resources (will be called implicitly in destructor of class. so it is a back up method  to make sure the unmanaged resources won’t leak  )


  • Dispose() is explicitly clean up unmanaged resources 



 



As an example, consider a class that holds a database connection instance. A developer can call Dispose on an instance of this class to release the memory resource held by the database connection object. After it is freed, the Finalize method can be called when the class instance needs to be released from the memory.



 



 









0 Comments:

Post a Comment

<< Home