Welcome to MSDN Blogs Sign in | Join | Help

Todd's Blog

My contribution to the SharePoint community
The Wait Class

Back when I did most of my coding with C++ I really liked the simplicity and compactness of using class constructors and destructors to do simple tasks such as setting a wait or busy cursor. For example, consider the code in Figure 1. It is a compact and simple API that is very easy to use and hard to use incorrectly.

void SomeClass::SomeMethod()
{
  //at this point the constructor would run and set our
  //cursor to busy.

  CWaitCursor cur;


  //do some work here

 
}//at this point the destructor would run setting our
//cursor back to its original state.
Figure 1

Today however I use C# as my primary development language and wanted to keep with what I knew worked in the C++ world so well. Since the CLR does not run the destructors (or finalizers) on its objects at predictable times there needed to be some modification to how I would implement and use the C# version of CWaitCursor (Figure 2).

internal class Wait : IDisposable
{
  Cursor _savedCursor;
  Form _form;

  public Wait(Form form)
  {
    if(form == null)
      throw new ArgumentException("form");

    _form = form;
    _savedCursor = _form.Cursor;
    _form.Cursor = Cursors.WaitCursor;
  }

  public void Dispose()
  {
    _form.Cursor = _savedCursor;
    
  }
}
Figure 2

Now to use my Wait class all I need to do is instantiate a new instance within one of my Forms, pass a reference to that form and use the "using" construct offered by the C# language.

public void SomeMethodOfAForm()
{
  using(new Wait(this))
  {
    //do some work here


  }
}
Figure 3

Ok at this point I should say I don't want to get into any debate with anyone over which language is better, which method is more preferred, etc... I will also point out before I am sure someone else will that this cannot be used with ASP.NET, ok you got me!

Correction: Rico was kind enough to point out that my Wait class was not finalizable so I did not need to SuppressFinalize on it.

Posted: Wednesday, January 04, 2006 8:31 AM by Toddca

Comments

No Comments

New Comments to this post are disabled
Page view tracker