Sunday, February 15, 2009

To Dispose or Not To Dispose is the Question

Answer - Do not call the Dispose() method on SPWeb, if you obtain the SharePoint SPWeb using the GetContextWeb method as shown below. If you call Dispose() on the SPWeb object obtained this way, it may cause the SharePoint object model to behave unpredictably or fail. This is due to an internal list that is kept in the SPSite and SPWeb objects derived in this way. Internally, the object model enumerates over this list after page completion to dispose of the objects properly.

web = SPControl.GetContextWeb(Context)

Here is a link to a best practices article titled "Best Practices: Using Disposable Windows SharePoint Services Objects"

http://msdn.microsoft.com/en-us/library/aa973248.aspx

Microsoft has a tool called, SPDisposeCheck, that will evaluate compiled assemblies and identify improper usage of SharePoint objects (such as SPWeb and SPSite) in your code. These objects, if improperly used, will cause memory leaks.

Here are links relevant to SPDisposeCheck:

http://code.msdn.microsoft.com/SPDisposeCheck

http://blogs.msdn.com/sharepoint/archive/2009/01/29/spdisposecheck-released.aspx

http://blogs.msdn.com/rogerla/archive/2009/01/29/automate-sharepoint-dispose-code-reviews-with-spdisposecheck.aspx

No comments: