Any SharePoint developer with about a days worth of SharePoint development knowledge tends to find out that you need to dispose of the SPWeb and SPSite objects.  Of course this is further conveluded by the fact that this isn't ALWAYS the case depending on whether your a webpart or not, context, etc. etc.

I was answering a few forum postings this evening when someone asked the question again, whether or not they should dispose something in a certain case. I think I sufficiently answered their post on the MSDN forum.

I thought that I would share the info again though on my site so that I can easily link to it later.

Roger Lambs SPWeb/SPSite dispose write up
Roger Lambs SPWeb/SPSite dispose when using try/finally blocks
Steve Gossner's SPWeb/SPSite dispose write up has some good tidbits about other objects that need disposing
MSDN's SPWeb/SPSite dispose write up

In addition MS is coming out with a tool that is basically like FxCop that will check for SPWeb/SPSite objects, but its not out yet. MS SharePoint Team Blog  word on the street is that its coming out very soon.

The tricky thing that most of the articles don't really discuss that much, is when you use statements like"item.ParentList.ParentWeb.RoleDefinitions" that it technically creates an SPWeb object in your method when you call the ParentWeb. You therefore should probably break that line out to something like


using(SPWeb parent = item.ParentList.ParentWeb)

{

//your code here

}


It is a well know fact that the SPSite and SPWeb objects need to be properly disposed of when using them in your API coding.  MSDN and the SDK typically tells you that when you see anything referencing those 2 objects.  The reason is that behind the scenes they have a reference  to a SPRequest object which uses a SharePoint COM object which isn't automagically disposed for you.  All the examples on MSDN and in the SDK show how to use the "using" statement, or manually calling "Dispose()" on the objects, but they don't really offer any other info than that.

Today I ran across a few REALLY good blog postings about this topc.  The first, by Stefan Gobner, shows how to do some troubleshooting, which is DEFINETELY worth a read.  He shows how you can go into the ULS logs, find certain error messages, and really track down the code that you wrote to find where you might not properly be disposing of the suspect objects.  You can find that article here, I strongly suggest reading it.

The second article, written by Roger Lamb, is actually linked from Stefan's blog and goes into a LOT more detail about pretty much all the objects that need to be disposed, and shows a lot more than MSDN/SDK does.  You can find that article here.


Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2017 Tony Testa's World