Pages

Subscribe:

Wednesday, December 14, 2011

Disposing SharePoint Objects

If you are using SharePoint object model, then it is very much important to correctly release resources. 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 ina 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/finaly code block or you can explicitely 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;
try
{
site = new SPSite("URL of the Site Collection");
// Code here
}
finally
{
if (site != null)
site.Dispose();
}

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.

No comments:

Post a Comment