Interesting SPWeb leak pattern with Areas in SPS 2003

Recently I came across another very interesting coding pattern which is very similar to the interesting SPSite leak I showed a couple of days ago.

public void workOnArea(Area area)
{
      if (area.Web != null)
      {
            string url = area.Web.Url;
            area.Web.Dispose();
      }
}

On a first look the code look ok, right? Ok, no try/catch blog and so on but for normal operations it looks as if the SPWeb object objects used from the Area object are correctly disposed, right?

The problem here is hidden in the internal implementation of the Web property of the Area object. What happens under the hood is that for every single use of Area.Web a new independent SPWeb object is created.

That means the code above creates 3 SPWeb objects – but only disposes one.

A correct implementation of the code would look like this:

public void workOnArea(Area area)
{
      SPWeb web = area.Web;
      if (web != null)
      {
            string url = web.Url;
            web.Dispose();
      }
}

That will ensure that only one single SPWeb object is created, reused and finally disposed.

Ok, completely correct it should be something like this:

public void workOnArea(Area area)
{
      using (SPWeb web = area.Web)
      {
            if (web != null)
            {
                  string url = web.Url;
            }
      }
}

Here you can find more coding patterns which need to be avoided:

http://blogs.msdn.com/rogerla/archive/2008/02/12/sharepoint-2007-and-wss-3-0-dispose-patterns-by-example.aspx

2 Comments


  1. Isn’t the using statement and the explicit Dispose call redundant, or did you mean not to include the explicit Dispose call in your last example?

    Reply

  2. Hi Joe,

    you are right! Forgot the remove it.

    It is now corrected.

    Cheers,

    Stefan

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.