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:
Permalink
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?
Permalink
Hi Joe,
you are right! Forgot the remove it.
It is now corrected.
Cheers,
Stefan