While writing the code with SharePoint Server Side Object Model, I an often stuck with a question “What objects, should I be responsible for disposing of?”
Though this seems to be a simple question I found it worth researching to extract the list of all the objects for which a developer is responsible to dispose of in order to avoid any memory leaks in the Farm.
In order to simplify the story, I have divided SharePoint objects in the three categories given below.
List of objects, which must be disposed 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, which must be closed (not disposed) explicitly:
- PublishingWeb created by PublishingWeb.GetPublishingWebs[] index operator.
- PublishingWeb created by PublishingWeb.GetVariation.
- PublishingWeb created by PublishingWebCollection.Add.
List of objects, which must never be disposed 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 the following two constructs available, which 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)
- {
- }
2. Use “Try, Catch & Finally Block”.
- try {
- SPWeb oWeb = osite.RootWeb;
- } catch (Exception ex) {
- throw;
- } finally {
- oWeb.Dispose();
- }
Hope, you find it helpful.