Friday, June 6, 2008

IDisposable Pattern in .NET

In some cases we also need to implement IDisposable pattern in our code.

For example, If you have unmanaged objects such as (File, Image, TCP Connection, etc) or you want to make sure that you have closed your connection / web service.

Here is the code

#region IDisposable Pattern
/// <summary>
///
Desctructor in VB.NET - Finalize
/// It will be called by Garbage Collector
/// or you may force GC by calling GC.Collect()
/// </summary>
~MyClass()
{
//only dispose unmanaged obj, for managed obj,
//it probably already been clear by GC,
//so we cannot called it again.
Dispose(false);
}
/// <summary>
///
Will be called when you use 'using'
/// keyword or implicitly called by you obj.Dispose()
/// </summary>
public void Dispose()
{
Dispose(true);
//tell GC not to run Desctrutor,
//because it has been called implicitly
GC.SuppressFinalize(this);
}

/// <summary>
///
Dispose Unmanaged and manage
/// </summary>
/// <param name="bDisposeManaged">
///
true - dispose unmanaged and managed code as well
/// fase - dispose only and unmanaged
/// </param>
protected virtual void Dispose(bool bDisposeManaged)
{
try
{
if (bDisposeManaged)
{
//TODO: dispose managed code
//Such as(Service, connection, etc)
if (_ServiceUser != null)
{
try
{
_ServiceUser.Dispose();
}
catch { }
}
}
//TODO: dispose unmanaged code
//such as (File, Bitmap / Image, TCP Connection, etc)
}
catch{}
}
#endregion

No comments: