IDisposable as a Wrapper
I needed to make a bunch of webservice calls from a WinMobile 6 device. None of the calls are particularly heavy, but I wanted to give some feedback that something behind the scenes was going on, otherwise the user gets confused about why he can’t click on things.
My first iteration was this ugly custom Form that took two callbacks as parameters. The first call back did the real work, the second was called after completion so that the UI thread could do something with the results. It was verbose, ugly, unreadable, and confusing. Don’t do that.
Furthermore, it turns out all that marshalling data around between UserWorkItem threads and the UI thread made the service call appear to be taking far longer than it really was. Color me unsurprised.
Duh. Windows has had this ability for over a decade: the WaitCursor
.
On a Mobile device, at least the model I’m using, this is rendered as a colorful spinner in the center of the screen. Moral of the story? Read the docs.
I didn’t feel like wrapping all the Service Calls with:
Cursor.Current = Cursors.WaitCursor;
callWebService();
Cursor.Current = Cursors.Default;
Talk about tedious. So I came up with this scheme:
public class WaitHelper : IDisposable
{
public WaitHelper() { Cursor.Current = Cursors.WaitCursor; }
public void Dispose() { Cursor.Current = Cursors.Default; }
}
Then to use it,
using(new WaitHelper())
{
callWebService();
}
This has the added benefit that Cursor.Current
will be set back to Cursors.Default
inside a finally
block, so even if the service throws, you don’t have to remember to set it back yourself.
This does however allocate a bunch of tiny, insignificant and data-less objects all over the place. Though perhaps the compiler or the jitter is smart enough to ignore it and inline the methods.
I don’t care though. I like it.