Reader Level:
ARTICLE

Using Dispose method in C#

On February 17, 2006 Articles | How do I
This artice will explain about Finalize and Dispose method implementation in C#.
  • 1
  • 0
  • 162052

This peice of code will show you some memory management in classes.

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.

using System;

namespace disposeConsole

{

          class ResourceManagement : IDisposable

          {

                   public ResourceManagement()

                   {}

                   private bool IsDisposed = false;

                   public void Free()

                   {

                             if (IsDisposed)

                                      throw new System.ObjectDisposedException("Object Name");

                   }

                   //Call Dispose to free resources explicitly

                   public void Dispose()

                   {

                             //Pass true in dispose method to clean managed resources too and say GC to skip finalize
                             in next line.

                             Dispose(true);

                             //If dispose is called already then say GC to skip finalize on this instance.

                             GC.SuppressFinalize(this);

                   }

                   ~ResourceManagement()

                   {

                             //Pass false as param because no need to free managed resources when you call finalize it
                             will be done

                             //by GC itself as its work of finalize to manage managed resources.

                             Dispose(false);

                   }

 

                   //Implement dispose to free resources

                   protected virtual void Dispose(bool disposedStatus)

                   {

                             if (!IsDisposed)

                             {

                                      IsDisposed = true;

                                      // Released unmanaged Resources

                                      if (disposedStatus)

                                      {

                                                // Released managed Resources

                                      }

                             }

                   }

          }

} 

Ashish Singhal

Ashish has been working as a software engineer since 2002. He has written articles for C# Corner . He specializes in the implementation of client/server, database, graphics and/or Internet-based syste...

  • 214rank
  • 1M readers
COMMENT USING

Trending up