Tuesday, August 23, 2011

Disposing SharePoint Objects

If you are using SharePoint object model, then it is very much important to correctly release resources.

Also you can check out some posts on:

- Get list level content types using SharePoint 2010 client object model

- AllowUnsafeUpdates in SharePoint 2010

- How to deploy sandboxed solution in SharePoint 2010?

It should ensure that any unmannaged resources should be released as soon as they are no longer needed. Though garbage collector automatically releases memory allocated to unused objects, but it will release in a unpredictable manner. The .NET Framework provides the IDisposable interface, which exposes a Dispose method that you should call to explicitly release these unmanaged resources. To invoke Dispose method, you can use the using keyword, you can use the try/finally code block or you can explicitly invoke Dispose method.

Example of using keyword:
using (SPSite site = new SPSite("URL of the Site Collection"))
// Code here

Internally the compiler converts the using block to try/finally block as shown below.
SPSite site = null;
site = new SPSite("URL of the Site Collection");
// Code here
if (site != null)

The SPSite and SPWeb types both implement the IDisposable interface, and both allocate unmanaged memory. If you do not correctly release SPSite and SPWeb instances, you will probably experience memory leaks, crashes, and frequent application pool recycles.

But if they are derived from the context object then the framework will take care of releasing resources, you should not release the resources.
For example SPWeb web = new SPSite(SPContext.Current.Web.Url).OpenWeb().
Here the web object is derived from the SPContext, so we should not dispose that. Here SPWeb object web.Dispose() automatically called.

You can also check a good article on SharePoint 2010 Best practices.

You can also check for the SPDisposeCheck for memory leaks.

you can check more in the msdn article.