Wednesday, February 4, 2009

Coding Style: WaitCursor encapsulation

Often during long processes, we need to display the WaitCursor to give feedback to the users. Changing the mouse cursor to WaitCursor, and then back to the default cursor may be achieved as follows:

1// change to WaitCursor

2Cursor.Current = Cursors.WaitCursor;

3

4// DO SOMETHING

5

6// change to default cursor

7Cursor.Current = Cursors.Default;

Now, assume that an exception is thrown during the processing (i.e. DO SOMETHING), the cursor may never change back to the default state. Hence, we may need to use a try and finally block to ensure that the cursor is changed back when either the processing is successfully completed or an exception is thrown. The code will now be as follows:

1// change to WaitCursor

2Cursor.Current = Cursors.WaitCursor;

3

4try

5 {

6// DO SOMETHING

7 }

8finally

9 {

10// change to default cursor

11Cursor.Current = Cursors.Default;

12 }

As changing the cursor to the busy state and back to the normal state is repeated in different methods, a further improvement would be to encapsulate this piece of functionality in a class. Then, a using statement can be used to handle the cursor states during processing.