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

2 Cursor.Current = Cursors.WaitCursor;

3

4 // DO SOMETHING

5

6 // change to default cursor

7 Cursor.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

2 Cursor.Current = Cursors.WaitCursor;

3

4 try

5 {

6 // DO SOMETHING

7 }

8 finally

9 {

10 // change to default cursor

11 Cursor.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.

23 /// <summary>

24 /// Handles wait cursor

25 /// </summary>

26 public class WaitCursor : IDisposable

27 {

28 public WaitCursor()

29 {

30 Cursor.Current = Cursors.WaitCursor;

31 }

32

33 public void Dispose()

34 {

35 Cursor.Current = Cursors.Default;

36 }

37 }




1742 using (new WaitCursor())

1743 {

1744 // DO SOMETHING

1745 }

1 comment:

Paul Diston said...

Hi,
Thank you very much for that tip. I can see it being very useful in the future.
Paul Diston