As a SharePoint developer, almost of time you will work with SharePoint object model. Some time you realize that your customize solution make SharePoint performance slow down. It is very important time to think about memory

it is very important to consider for the memory used by your code via these SharePoint objects which was implemented IDisposable interface. It means these types of objects must be disposed right after finish you request for accessing data as soon as possible.

From 2009, Microsoft introduced some guidelines for coding and working with SharePoint object module and SPDisposeCheck is a great utility for checking the disposal patterns for your SharePoint solution, it’s also a helpful utility when you need to review a large of source code from your team.

The latest version of SPDisposeCheck tool has support as Add-in for Visual studio 2008/2010. So you can run SPDisposeCheck when building your Visual Studio project.

You can visit here to get for latest version: http://archive.msdn.microsoft.com/SPDisposeCheck

You can check Roger Lamb’s blog for SPDisposeCheck development team http://blogs.msdn.com/b/rogerla/

There are also couple of White Papers by Scott Harris’s on MSDN for more details:
Best Practices: Using Disposable Windows SharePoint Services Objects
Best Practices: Common Coding Issues When Using the SharePoint Object Model.

Most usually we forgot in our code dispose SPWeb or SPSite object after the new operator

//for SPSite
void CreatingSPSiteLeak()
{
    SPSite siteCollection = new SPSite("http://moss");
    // siteCollection leaked
}

//for Open SPWeb
void OpenWebLeak()
{
    using (SPWeb web = new SPSite(SPContext.Current.Web.Url).OpenWeb())
    {
      // SPSite leaked !
    }
}

//for AllWeb
void AllWebsIndexerLeak()
{
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        SPWeb web = siteCollection.AllWebs[0];
        // SPWeb web leaked
    }
}

//for Add SPWeb
void AllWebsAddLeak()
{
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        SPWeb web = siteCollection.AllWebs.Add("site-relative URL");
        // SPWeb web Leaked
    }
}
//And many others scene...

Manually configure run SPDisposeCheck as external tool

Implement as below configure

Manually configure run at compile time

Find all projects under the solution that reference the Microsoft.SharePoint namespace and select properties on the project file. Select the Build Events tab and enter the commands below into the Post-build events text box for On Successful Build:

cd $(ProjectDir)

“..\SharePoint Dispose Check\SPDisposeCheck” “$(TargetPath)” > “$(ProjectName)”.SPDisposeCheck.log

findstr /C:”Total Found:” “$(ProjectName)”.SPDisposeCheck.log


More information about the proper disposal of SharePoint objects, see this article

Hoang Nhut Nguyen
Email: nhutcmos@gmail.com
Skype: hoangnhut.nguyen