#430 – A Dispose Pattern Example

If you want to control when an object’s unmanaged resources are released, you can follow the dispose pattern, implementing a Dispose method.

Here’s a complete example.  We create a method to release resources that is called either when a client invokes Dispose directly or when the CLR is finalizing the object.

    public class Dog : IDisposable
    {
        // Prevent dispose from happening more than once
        private bool disposed = false;

        // IDisposable.Dispose
        public void Dispose()
        {
            // Explicitly dispose of resources
            DoDispose(true);

            // Tell GC not to finalize us--we've already done it manually
            GC.SuppressFinalize(this);
        }

        // Function called via Dispose method or via Finalizer
        protected virtual void DoDispose(bool explicitDispose)
        {
            if (!disposed)
            {
                // Free some resources only when invoking via Dispose
                if (explicitDispose)
                    FreeManagedResources();   // Define this method

                // Free unmanaged resources here--whether via Dispose
                //   or via finalizer
                FreeUnmanagedResources();

                disposed = true;
            }
        }

        // Finalizer
        ~Dog()
        {
            DoDispose(false);
        }
    }

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

4 Responses to #430 – A Dispose Pattern Example

  1. Pingback: #737 – When to Implement a Finalizer « 2,000 Things You Should Know About C#

  2. chaitanya says:

    A quick question, why is the method DoDispose protected and virtual? Could you please explain the specific reason?

    thanks,
    chaitanya

    • Sean says:

      It’s protected so that a child class can call it, if desired. It’s virtual so that a child class can override it as a virtual method. Being virtual, the DoDispose logic in the parent class will then correctly invoke the method in the child class.

  3. Pingback: Object Disposal and BackgroundWorker Object in .NET | Sean's Stuff

Leave a comment