Introduction:
IDisposable Interface is primarily designed to provide a standard way to manage the unmanged resources in the .net applications.
Description:
We know that Garbage Collector(GC) is designed to manage memory allocation in .net applications. So developer have no headache to manage the managed resources as GC manage it implicitly. But when it comes about the unmanaged resources GC have no control over it, because GC is not designed to deal with unmanaged resources, so it is the developers responsibility to manage this unmanaged resources.
A developer can achieve this by overriding the Finalize method, but the problem with finalize method is that as Garbage Collector does not run in deterministically and in result the object may be wait for finalization for a longer period of time. And this situation becomes more complected if our object is using expensive resources like database connection or file handles, then waiting a long period of time to free these resource is not acceptable. To avoid this waiting of Garbage Collection for an indeterminate amount of time to free resource Disposable Pattern (IDisposable pattern) is used.
This Disposable Pattern/IDisposable Interface is basically designed to ensure predictable and reliable cleanup of resource to prevent resource leak and to provide a standard pattern for disposable classes. IDisposable interface defines a single method called Dispose() that need to be implemented by the implemented class. And the developers have to ensure that they implements clean up code using this method.
Example:
public class MyDisposableClass : IDisposable
{
private bool isDisposted = false;
~MyDisposableClass()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (!isDisposted)
{
if (disposing)
{
//TODO: Wtire your clean up code here
//This will remove the object from the finalization queue as the clean up
//is already done and finaliztion is not required.
GC.SuppressFinalize(this);
}
// flag set to ture as dispose is done
isDisposted = true;
}
}
}
No comments:
Post a Comment
Your comments are valuable.