The "using" pattern

In the previous post, I’ve discussed how I misused the IDisposable.Dispose() method. Here, I will present some of the ways I use the using keyword in manners that may don’t come to mind at first (I may in a few years come back to this and realize I was totally wrong, but for now, it seems to me the samples provided here may prove usefull).

According to msdn, the using statement “Defines a scope, outside of which an object or objects will be disposed“. In the remarks section of the documentation, it is also stated that “The using statement allows the programmer to specify when objects that use resources should release them“. And the next sentence: “The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object’s resources“. Everything’s ok about all this, expect one little thing: by insisting on resources, it drives people to use the using keyword only with objects holding resources, or locks, or connections or whatever needs to be released to the system…

I think this statement can be used in an extensible manner for any object that:

  • lives in a finite scope
  • needs an action to be done when created and another one when you don’t need it any more.

For instance, when it’s dark, and I want to write something, I need some light. So I turn it on, write my post, and turn it off before going to bed. This could be writtent this way in C#:

SwitchOnLight();
WriteThisPost();
SubmitIt();   
SwitchOffLight();
GotoBed();

There are times when I’m quite tired, and I may forget to switch off the light before going to bed. This results in this code:

SwitchOnLight();
WriteThisPost();
SubmitIt();   
GotoBed();

Here, C# programmers will have recognized that some kind of Dispose() call is missing. Enters the using keyword which allows me to write:

using(Light)

    WriteThisPost();
    SubmitIt();    
}
GoToBed();

And thus, I never forget to turn off the light before going to bed.

I really like the metaphor the using keyword provides, and I’d like to be able to use it even for objects that don’t hold any system resource. As the samples below demonstrate it, there’s nothing preventing me from doing so. The main idea is that any object that needs to do something when created, and something else when released is a good candidate for the using keyword: these two tasks are implemented in the constructor and in the IDisposable.Dispose() method. The task executed in the Dispose() method hasn’t to release resources. In fact, most of the times, It just restores a saved state.

Example 1:

In most of my windows forms applications, I use a base form class providing some goodies to inheritors (one of them is a wonderfull linear gradient I apply on the background of my forms – question of taste). Among these services is WaitCursor. Usually when you want to show an hourglass cursor while processing a lengthy task, you have to follow three steps:

  1. Change the cusor: this.Cursor = Cursors.WaitCursor;
  2. Execute the lengthy task in a try block
  3. Restore the normal cursor in a finally clause: finally { this.Cursor = Cursors.Default; }

I’ve built up a little helper class (completed with a property) which allows you to write this code, (which seems more readable to me : it’s almost well formed English):

using(WaitCursor) { /* execute lengthy task */ }

First, in the base form class, WaitCursor is a property returning an IDisposable:

protected IDisposable WaitCursor
{
         get { return new CursorProvider(this, Cursors.Wait); }
}

And CursorProvider is a private inner class also defined in the base form class:

private class CursorProvider : IDisposable
{
        Control owner = null;
        Cursor savedCursor = Cursors.Default;

        public CursorProvider(Control control, Cursor newCursor)
        {
            if (control == null)
                throw new ArgumentNullException(“control”);
            if (newCursor == null) 
                throw new ArgumentNullException(“newCursor”);

            owner = control;
            savedCursor = control.Cursor;
            control.Cursor = newCursor;
            control.Refresh();
        }

        #region IDisposable Members

        public void Dispose() { owner.Cursor = savedCursor; }

        #endregion
}

A few explanations:

  • The property is returning an IDisposable instance: indeed, callers don’t have to know anything else (it is intendeed to be part of a using statement) so, why would I expose more?
  • Each time the property is called, a new object is created: you can overlap as many using statements as you wish, after the last closing bracket, the correct cursor will be restored.
  • We never need the object created by the call to the property, thus the using(WaitCursor) and not some using(IDisposable foo = WaitCursor).
  • The class is straightforward: the constructor, after checking for null parameters, saves the current state (the current control’s cursor) then sets the new state. Inside Dispose() (which will always be called at the end of the using block, wether an exception has been thrown or not), the state is restored.

Example 2: Saving the state of a Graphics object. In this old post, I exposed a way of using the GraphicsContainer class. And I wrapped it in an IDisposable object (one time again, the idea is to save a state in the constructor, and to restore it in Dispose()).

Example 3: .NET Matters: Scope and more. In this article from MSDN Magazine, Stephen Toub explains how to code a Scope<T> class to provide transactionnal behavior. This is an advanced example of a class that fits perfectly well with the using syntax. Besides the link with this post regarding the using statement, this article also discusses many other interesting .NET concepts (and in particular, the notion of thread static members). The second short article about the Semaphore class is again an example of a pretty use of the using statement.

Mea culpa: the IsDisposed anti-pattern

Back a few years ago, when I was still a new-born at C# and .NET programming, I had found myself very proud for having improved the .NET framework itself. Indeed, I had just invented the IDisposableEx interface:

public interface IDisposableEx : IDisposable
{
     bool IsDisposed { get; }
}

What did I use this interface for? It seemed to me a great improvement to be able to know whether or not an object had been disposed. And I was writing code like this:

if (!myObject.IsDisposed) myObject.Dispose();

Here lie two style errors:

  1. Not so a serious one: why calling Dispose() when a using construct would make it perfectly useless (As of now, I only call Dispose() when the object is not instanciated in the method that will dispose it)?
  2. The real big one: what is the use of the test on the disposed state of the object? Microsoft clearly states that a Dispose() method call should NEVER EVER fail (see msdn). One could call Dispose() thousands of times, there should never happen any exception. So, the test is useless.

On the other hand, one could argue that testing the disposed state of the object isn’t that serious… and I agree with this; in fact, what is really misconcepted in the IDisposableEx interface is not how you use it, but what it supposes can happen inside the implementor: by allowing to test the disposed state, this interface suggests that the behavior of the Dispose() method depends on the state of the object. And even worse: if you call Dispose() and the IsDisposed property was true, then Dispose() might fail! And in some of my implementations, it did! In my mind providing a means of testing was good enough, and if your app ended with an uncaught exception, it was the developper’s fault: why didn’t you test IsDisposed?… my apologies go to them… 

The correct way to handle multiple calls to Dispose() is actually to store a disposed state, but it must be inner to the object and calling code must never rely on it (so I’d  better make this private, and remove the IDisposableEx interface – from source control if I can, so that no one ever discovers my crime):

private bool disposed = false;

public void Dispose()
{
    if (disposed) return;

    // disposing of allocated resources
    …
    // now, don’t forget to set the disposed state

    disposed = true;
}

I hope that having revealed a part of my dark past will help you not to make that mistake, or at least will it have made you laugh a bit.

 

PS: I can’t think of a scenario right now where a caller should be aware of the disposed state of the callee, but in such a case, the IsDisposed property seems acceptable (if you don’t want to catch numbers of ObjectDisposedException). But I think this would be a really bad idea to provide this property as part of an interface… Or at least should this interface be named something like IDisposedStateNotifier so that developpers don’t think it modifies the IDisposable.Dispose standard behavior…