Below I put together a quick reference of the known SharePoint properties and methods that you do not want to call Dispose against when developing SharePoint applications (AKA “Do Not Dispose Guidance”). Please check back on this blog post as I will be keeping it updated as we move closer to the SharePoint Server 2010 Release second half of 2010. I am communicating directly with the SharePoint Product Team and plan on validating the existing guidance for Microsoft Office SharePoint Server 2007. If you have additional questions on items you don’t see here please feel free to leave comments on this blog with code samples.
SPDisposeCheck: The current version v1.3.1 (January 2009) of SPDisposeCheck utility does not scan for “Do Not Dispose Guidance”. SPDisposeCheck does a great job drawing your attention to areas of your source code that potentially do not conform with our (Microsoft’s) guidance on Disposing SharePoint objects but you might not be fully aware that it’s not going to report any of the “Do Not Dispose Guidance” listed below. Until we release the refreshed version of SPDisposeCheck that targets “Do Not Dispose Guidance” you will need to manually review the source code for the guidance on my blog and our Dispose WhitePaper. The current version of SPDisposeCheck was targeted and tested against Microsoft Office SharePoint Server 2007 but we are working on a update that works with SharePoint Server 2010 Beta 2.
Remember it’s best practice to regularly review your ULS logs for Dispose() related leaks that have occurred during runtime.. SharePoint Server internally is instrumented to report on Dispose related leaks.
“Do Not Dispose Guidance” as of 11/30/2009:
SharePoint 2007 & 2010:
- Do not call list.ParentWeb.Dispose()
- Problems may occur when SPContext.Web has equality to the SPContext.Web.. make sure you dispose of SPSite and it will cleanup sub webs automatically
- When used with WSS 3.0 you must call Dispose(), with SharePoint Foundation 2010 you don’t.
- Event Receivers and properties.OpenWeb()
- WSS 3.0: When you call properties.OpenWeb() the returned SPWeb will need to call Dispose()
- SharePoint Foundation 2010: Use the newly introduced SPItemEventProperties.Web property instead of SPItemEventProperties.OpenWeb() for better performance and to avoid the need to call Dispose().