Geeks With Blogs

News Coming soon!

Code Without Fear Ruminations by Don Huff

Resource Acquisition Is Initialization (RAII) is a pattern I grew to love when working in C++.  It is perfectly suited for resource management such as matching all those pesky new's and delete's.  One of my goals was to limit the explicit deallocation statements I had to write.  Often these statements became victims of run-time control flow changes (i.e. exceptions, unhappy path) or development-time code refactoring.

The beauty of RAII is realized by tying your resource creation (acquisition) to the construction (initialization) of a class instance.  Then bind the resource deallocation to the destruction of that instance.  That is well and good in a language with strong destructor semantics like C++, but languages like C# that run on garbage-collecting runtimes don't provide the same instance lifetime guarantees.

Here is a class and sample that combines a few features of C# to provide an RAII-like solution:

using System;

namespace RAII
{
    public class DisposableDelegate : IDisposable
    {
        private Action dispose;

        public DisposableDelegate(Action dispose)
        {
            if (dispose == null)
            {
                throw new ArgumentNullException("dispose");
            }

            this.dispose = dispose;
        }

        public void Dispose()
        {
            if (this.dispose != null)
            {
                Action d = this.dispose;
                this.dispose = null;
                d();
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.Out.WriteLine("Some resource allocated here.");

            using (new DisposableDelegate(() => Console.Out.WriteLine("Resource deallocated here.")))
            {
                Console.Out.WriteLine("Resource used here.");

                throw new InvalidOperationException("Test for resource leaks.");
            }
        }
    }
}

The output of this program is:

Some resource allocated here.
Resource used here.

Unhandled Exception: System.InvalidOperationException: Test for resource leaks.
   at RAII.Program.Main(String[] args) in c:\Dev\RAII\RAII\Program.cs:line 40
Resource deallocated here.

Code without fear!

--Don

Posted on Thursday, June 28, 2012 1:55 PM CSharp , Pattern | Back to top


Comments on this post: Resource Acquisition is Initialization in C#

# re: Resource Acquisition is Initialization in C#
Requesting Gravatar...
I wonder how many times this has been invented. :-) I posted something similar a couple months ago. (http://www.skylark-software.com/2012/04/there-and-back-again-again-any.html)

While this technique is good given what we have to work with, I still think the use of Dispose is a really ugly hack. You have to know it's needed for it to be any help. It's not really in the same ballpark as deterministic destructors combined with RAII.

Cheers.
Left by Harley Pebley on Jun 29, 2012 1:48 PM

# re: @Harley
Requesting Gravatar...
Very similar solutions indeed. I agree it would be nice to have a more direct means of realizing stack-based lifetime processing without resorting to try/finally or IDisposable/using ugliness.
--Don
Left by Don on Jul 01, 2012 5:44 PM

Your comment:
 (will show your gravatar)


Copyright © codeWithoutFear | Powered by: GeeksWithBlogs.net