Rob Garrett - Blogs

Welcome to Rob Garrett - Blogs Sign in | Join | Help
in Search
Google

Software/Technology Discussion

Software and Technology Tid-bits

Bak 2 Basiks - Design Patterns - The Dispose Pattern

Continuing on with the Design Patterns theme - see my last post in this series here - this post is a favorite of mine, mainly because it is is specific to .NET and also because it causes me mental block (for some reason), so what better place to put it for future reference than my blog.  

To understand the workings of this pattern it is important to know how the Garbage Collection Process works in .NET, and since it is an involved subject I shall not clutter this post with these details. 

Essentially this pattern cleans up both managed and unmanaged resources when users of this class call Dispose on object instances.  If the user neglects to call Dispose and the Garbage Collector kicks in, then the Finalizer does the clean up.  Of course, the special thing about finalizers is that they cannot reference managed objects.  This is because the GC may have already freed up the memory of these objects by the time the finalizer executes, hence the need for a disposing toggle and Dispose(boolean) method.

The comments explain all, if you have resource intensive objects in your .NET code be sure to implement this pattern.

public class Dummy : IDisposable
    {
        #region Fields

        private bool _disposed = false;

        #endregion Fields

        #region Destruction

        /// <summary>
        /// Cleanup.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            // Take yourself off of the finalization queue
            // to prevent finalization code for this object
            // from executing a second time.
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// This Finalize method will run only if the 
        /// Dispose method does not get called.
        /// </summary>
        public ~Dummy()
        {
            // Do not re-create Dispose clean-up code here.
            // Calling Dispose(false) is optimal in terms of
            // readability and maintainability.
            Dispose(false);
        }

        /// <summary>
        /// Dispose(disposing As Boolean) executes in two distinct scenarios.
        /// If disposing is true, the method has been called directly 
        /// or indirectly by a user's code. Managed and unmanaged resources 
        /// can be disposed.
        /// If disposing equals false, the method has been called by the runtime
        /// from inside the finalizer and you should not reference other    
        /// objects. Only unmanaged resources can be disposed.
        /// </summary>
        /// <param name="disposing">If true then user called dispose, otherwise finalizer called dispose.</param>
        private void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (!_disposed)
            {
                // If disposing equals true, dispose all managed and unmanaged resources.
                if (disposing)
                {
                    // Dispose managed resources.
                }
                // Release unmanaged resources. If disposing is false,
                // only the following code is executed.      
                // Note that this is not thread safe.
                // Another thread could start disposing the object
                // after the managed resources are disposed,
                // but before the disposed flag is set to true.
                // If thread safety is necessary, it must be
                // implemented by the client.

            }
            _disposed = true;
        }


        #endregion Destruction
    }
Share this post: Email it! | bookmark it! | digg it! | reddit!
Published Friday, May 25, 2007 11:10 PM by Rob Garrett
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

 

Chris Hynes said:

This is a great post about the finalize pattern. If you want more detail on the topic, I found a post that really digs down on this topic (more like an article lol) by Joe Duffy that has the best, most comprehensive information about Dispose, Finalization, and Resource Management. You can find his post here: http://www.bluebytesoftware.com/blog/PermaLink.aspx?guid=88e62cdf-5919-4ac7-bc33-20c06ae539ae
May 29, 2007 9:19 AM

Leave a Comment

(required) 
(optional)
(required) 
Submit

Blurb


Head Shot
Rob Garrett is a British Expat living in Maryland USA. Rob is a trained software engineer and experienced in Windows .NET development.

Rob enjoys listening to Rock music, posting to blogs, driving in the country with the sunroof open, beer (not in conjunction with country driving) and spending time with his family.

This Blog

Syndication

Powered by Community Server, by Telligent Systems