SharePoint: Closing SPWeb and SPSite objects

Within both SharePoint 2003 and 2007, SPWeb objects need to be explicitly closed or disposed of. I believe this is because SPWeb and SPSite object use unmanaged code, so .net garbage collection doesn’t ensure that such objects are removed from memory. If you don’t close these, you will get a memory leak.
On the majority of blog articles I have seen (and some msdn documentation e.g. http://msdn2.microsoft.com/en-us/library/ms473155.aspx), closing / disposal of SPWeb and SPSite objects does not occur. I can only speculate that this is because the memory leak encountered is not noticable, unless you are creating a lot of these objects.

SPSite mySite = new SPSite(mySiteUrl);
SPWeb myWeb = mySite.OpenWeb();
try
{
    // Do something...
}
finally
{
    if (myWeb != null)
    {
        myWeb.Close();
    }
    if (mySite != null)
    {
        mySite.Close();
    }
}

Alternatively, as SPSite and SPWeb implement IDisposable, you can use the Dispose method instead of the close method, or use a using block (which implicitly calls the Dispose method):

using (SPSite mySite = new SPSite(mySiteUrl))
{
    using (SPWeb myWeb = mySite.OpenWeb())
    {
        // Do something here ...
    }
}

See http://msdn2.microsoft.com/en-us/library/ms778813.aspx for more info. Also note that an SPList object does not have a close method.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>