Manage SharePoint object life cycle by using the Dispose API

Since the SharePoint object model uses a lot of unmanaged objects you should dispose them after you’re done working with them. The standard way in the .NET Framework to do so is using the IDisposable interface – so is in SharePoint.

As a standard rule of thumb: whenever you create a new instance of an SPSite or an SPWeb, you should dispose it. The same holds true if you acquire your SPSite or SPWeb through an indexer, a property or whatever EXCEPT when you get the instance via the SPContext class. SharePoint manages the current SPContext, and you should never release it. There’s one other exception: the disposal of SPSite.RootWeb is managed internally, you should not release it.

Now the preferred way is to use a using statement, like this:

using(SPSite site = new SPSite(“mysiteurl”))
{
using(SPWeb web = site.OpenWeb())
{
//do stuff here
}
}

The using blocks will be converted to appropriate try and finally blocks, so your unmanaged resources will be disposed. Of course you can use the try/catch/finally or try/finally pattern explicitly. In this case you should dispose your objects in the finally block, but be sure to check for null references first.

One last thing to consider: since Response.Redirect by default does not play well with finally blocks (e. g. finally won’t be called) you should dispose your objects explicitly before calling Response.Redirect.

Check out this series of blog posts about best practices with SharePoint and IDisposable.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s