SharePoint Best Practices: COM Objects Disposal
While writing the code with SharePoint Server Side Object Model I often stuck with a question “What all objects should I be responsible to get disposed of?”
Though this seems to be a simple question found it worth researching upon to extract the list of all the Objects for which a developer is responsible to get disposed of in order to avoid any memory leaks in the farm.
In order to simplify the story have divided SharePoint Objects following three categories:
List of objects that must be disposed of explicitly
- SPWeb Object created with SPSite.OpenWeb
- SPSite objects created with SPSite.SelfServiceCreateSite
- SPWeb created by SPLimitedWebPartManager
- SPSite created by SPSiteCollection.Add
- SPSite created by SPSiteCollection[] index operator
- SPWeb created by SPWebCollection.Add
- SPWeb created by SPWebCollection[] index operator
- SPSite created with UserProfiles.PersonalSite
List of objects that must be closed (not disposed of) explicitly
- PublishingWeb created by PublishingWeb.GetPublishingWebs[] index operator
- PublishingWeb created by PublishingWeb.GetVariation
- PublishingWeb created by PublishingWebCollection.Add
List of objects that must never be disposed of explicitly
- SPListEventProperties.Web
- SPWebEventProperties.Web
- SPItemEventProperties.Web
- SPItemEventProperties.ListItem.Web
- SPItemEventProperties.Web.Site
- SPItemEventProperties.ListItem.Web.Site
- SPFeatureReceiverProperties.Feature.Parent
- SPSite.RootWeb
- SPWeb.ParentWeb
- SPList.ParentWeb
- SPSite returned by SPControl.GetContextSite
- SPWeb returned by SPControl.GetContextWeb
- SPSite returned by SPContext.Current.Site
- SPWeb returned by SPContext.Current.Web
How to ensure proper disposal of an object after the job is done
There are following two constructs available that can ensure the disposal of SharePoint Objects even if any unforeseen runtime exception occurs in the code.
1. Use “Using Block”
using(SPWeb oWeb = osite.RootWeb)
{
}//oWeb will get disposed automatically as soon as using block ends
- Use “Try, Catch & Finally Block”
try
{
SPWeb oWeb = osite.RootWeb;
}
catch(Exception ex)
{
throw;
}
finally
{
oWeb.Dispose(); //oWeb will get disposed as soon as Dispose() method called.
}
Hope this will help someone in need.