Tip: Easily Automating use of WaitCursor

This is really simple and probably common, but it’s a useful tip anyway.

Say you need to set a form’s cursor to the wait cursor while you accomplish something.

You would do something like this:

this.Cursor = Cursors.WaitCursor;
 
//do something
 
this.Cursor = Cursors.Default;

Of course, what if “do something” throws an exception? Then your cursor won’t be set back to the default.

So let’s wrap it in try-finally.

try
{
    this.Cursor = Cursors.WaitCursor;
    //do something
}
finally
{
    this.Cursor = Cursors.Default;
}

Better, but that’s a lot of wrapping around a simple operation. Notice, that the try-finally is exactly the pattern that using is. Why not wrap this functionality into a simple to use class that handles the cursor reset automatically?

internal class WaitCursor : IDisposable
{
    private Control _control = null;
    public WaitCursor(Control control)
    {
        _control = control;
        _control.Cursor = Cursors.WaitCursor;
    }
    public void Dispose()
    {
        _control.Cursor = Cursors.Default;
    }
}

And to use it in a form is simple:

using (new WaitCursor(this))
{
    //do work
}

Of course, you could easily add functionality like restoring the previous cursor instead of always the default, handling exceptions, make it thread-aware so it uses Invoke if necessary, better error-handling, etc.

Technorati Tags: ,,,


Check out my latest book, the essential, in-depth guide to performance for all .NET developers:

Writing High-Performance.NET Code, 2nd Edition by Ben Watson. Available for pre-order:

2 thoughts on “Tip: Easily Automating use of WaitCursor

  1. Ovidiu

    Why not do like this?

    using (Cursors.WaitCursor)
    {
    //do work
    }

    The only improvement of your code is managing the cursor on an object basis. But while your application loads it keeps the main thread locked. So I doubt there are any improvements in user friendly-ness.
    If you are loading something in the background then you don’t need the WaitCursor, do you?

  2. Wurnla

    @Ovidiu

    Disposing an object (Cursors.WaitCursor), which you have not created, is bad practice.
    Furthermore it looks to me that you are disposing cursors as opposed to switching cursors. The former is certainly less effective.

Leave a Reply

Your email address will not be published. Required fields are marked *