Carl Franklin: So, are you telling me that you are responsible
for the dispose method?
Chris Sells: I am responsible for the "using" statement in C# too. But don’t blame me that’s not the solution that I asked for.
Anyway, it's not the traditional use of IDisposable that this post is about. I want to talk about an "interesting" use of the IDisposable pattern: some time ago (I want to say ~3 years ago) I discovered a technique (I think originally in the NUnit codebase, but cannot be sure). The easiest way to explain what I'm banging on about here is to show you (the first time I used this technique it was for setting the mouse cursor in Windows Forms):
public class WaitCursor : IDisposable
{
private Form _parent;
private Cursor _previousCursor;
public WaitCursor(Form parent)
{
this._parent = parent;
this._previousCursor = this._parent.Cursor;
SetCursor(Cursors.WaitCursor);
}
private void SetCursor(Cursor targetCursor)
{
if(this._parent == null) return;
this._parent.Cursor = targetCursor;
}
public void Dispose()
{
SetCursor(this._previousCursor);
}
}
The way you would then use this class would be:
using(new WaitCursor(this))
{
// ...do some work here that
// requires the "Hour Glass"
}
Once the block of code within the using has finished executing the cursor will be returned to its original state; this would more normally require a try-finally block to be used, which would reset the cursor in the finally block (leads to ugly code IMHO). When I first saw this technique I thought "That's brilliant!" and immediately stole it - my hope is that you do the same.

0 comments:
Post a Comment