Chưa phân loại

[C# Tutorial] – Using Dispose method

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

When we give application to client, we don’t 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.
                             //If dispose is called already then say GC to skip finalize on this instance.
                             //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.

                   //Implement dispose to free resources
                   protected virtual void Dispose(bool disposedStatus)
                             if (!IsDisposed)
                                      IsDisposed = true;
                                      // Released unmanaged Resources
                                      if (disposedStatus)
                                                // Released managed Resources

Happy coding!!



1 thought on “[C# Tutorial] – Using Dispose method”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s