Stefan Goßner

Senior Escalation Engineer for SharePoint (WSS, SPS, MOSS, SP2010) and MCMS

Interesting SPWeb leak pattern with Areas in SPS 2003

Interesting SPWeb leak pattern with Areas in SPS 2003

  • Comments 2
  • Likes

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

Comments
  • 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?

  • Hi Joe,

    you are right! Forgot the remove it.

    It is now corrected.

    Cheers,

    Stefan

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
Raw Html Fix